How to get the current date in Python
How to get the current date in Python.
Here's a step-by-step tutorial on how to get the current date in Python:
Import the
datetimemodule:- In Python, the
datetimemodule provides classes for manipulating dates and times. To use it, you need to import the module first. You can do this by adding the following line at the beginning of your code:import datetime
- In Python, the
Get the current date using
datetime.date.today():The
datetimemodule provides thedateclass, which has a static method calledtoday()that returns the current date. You can use this method to get the current date in the formatYYYY-MM-DD. Here's an example:import datetime
current_date = datetime.date.today()
print(current_date)
Format the current date using
strftime():If you want to format the current date in a specific way, you can use the
strftime()method. This method allows you to specify a format string that defines how the date should be displayed. Here's an example that formats the current date asDD/MM/YYYY:import datetime
current_date = datetime.date.today()
formatted_date = current_date.strftime("%d/%m/%Y")
print(formatted_date)
Get the current date and time using
datetime.datetime.now():If you also need the current time along with the date, you can use the
datetimeclass from thedatetimemodule. Thenow()method returns adatetimeobject representing the current date and time. Here's an example:import datetime
current_datetime = datetime.datetime.now()
print(current_datetime)
Format the current date and time using
strftime():Similar to formatting the date, you can also format the date and time using the
strftime()method. Here's an example that formats the current date and time asYYYY-MM-DD HH:MM:SS:import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
That's it! You now know how to get the current date in Python using the datetime module. Feel free to experiment with different formatting options to display the date and time in the desired format.