In this article, you will learn to get today's date and current date and time in Python. We will also format the date and time in different formats using strftime() method.
There are a number of ways you can take to get the current date. We will use the
date class of the datetime module to accomplish this task.
from datetime import datetoday = date.today()print("Today's date:", today)
Here, we imported the
date class from the
datetime module. Then, we used the
date.today() method to get the current local date.
By the way,
date.today() returns a
date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.
from datetime import datetoday = date.today()# dd/mm/YYd1 = today.strftime("%d/%m/%Y")print("d1 =", d1)# Textual month, day and yeard2 = today.strftime("%B %d, %Y")print("d2 =", d2)# mm/dd/yd3 = today.strftime("%m/%d/%y")print("d3 =", d3)# Month abbreviation, day and yeard4 = today.strftime("%b-%d-%Y")print("d4 =", d4)
When you run the program, the output will be something like:
d1 = 16/09/2019d2 = September 16, 2019d3 = 09/16/19d4 = Sep-16-2019
If you need to get the current date and time, you can use
datetime class of the
from datetime import datetime# datetime object containing current date and timenow = datetime.now()print("now =", now)# dd/mm/YY H:M:Sdt_string = now.strftime("%d/%m/%Y %H:%M:%S")print("date and time =", dt_string)
Here, we have used
datetime.now() to get the current date and time. Then, we used
strftime() to create a string representing date and time in another format.