Get current date and time in Python
There are serval ways we can use to get the current date. We will use the date
class of the datetime module to perform this task.
Example: Python get today's date
In the following example, we will get today's date.
from datetime import date
today = date.today()
print("Today's date:", today)
Output
Today's date: 2017-10-30
In the above code, we imported the date
class from the datetime
module. After, we used the date.today()
method to get the current local date.
The date.today()
method returns a date
object which is assigned to the today
variable. After getting the date
object, we can use the strftime() method to create a string representing date in diffrent formats.
Example: Current date in a different format
In the following example, we will display today's date in a different format.
from datetime import date
today = date.today()
# mm/dd/YY
x1 = today.strftime("%m/%d/%Y")
print("date 1 =", x1)
# mm/dd/y
x2 = today.strftime("%m/%d/%y")
print("date 2 =", x2)
# Textual month, day and year
x3 = today.strftime("%B %d, %Y")
print("date 3 =", x3)
# Month abbreviation, day and year
x4 = today.strftime("%b-%d-%Y")
print("date 4 =", x4)
After executing the above program, the output will be as follows:
date 1 = 10/30/2017
date 2 = 10/30/17
date 3 = October 30, 2017
date 4 = Oct-30-2017
Example: Get the current date and time
To get the current date and time, we can use the datetime
class of the datetime
module.
from datetime import datetime
now = datetime.now()
print("now =", now)
# mm/dd/YY H:M:S
dt_str = now.strftime("%m/%d/%Y %H:%M:%S")
print("date and time =", dt_str)
The output of the above code:
now = 2021-10-30 21:20:13.737047
date and time = 10/30/2021 21:20:13
Above, we have used datetime.now()
to get the current date and time. And after we used strftime()
to create a string representing date and time in another format.