Print current Date and Time in Python
In this post, let's see various ways of getting current date and time in Python:
1. Date
from datetime import date
now = date.today()
print("Date:", now) # prints today's date as Date: 2020-04-25
Run here
we have imported date class from the datetime module in the above example and then, we have used date.today()
method to get the current local date.
2. Current Date-time
import datetime
now = datetime.datetime.now()
print (str(now)) # prints 2020-04-25 05:04:21.659405
Run here
we have imported datetime class in the above example and then, we have used datetime.datetime.now()
method to get the current local date-time.
3. Date and Time in different formats
strftime()
method is used to format date in your desired format.
from datetime import date
now = date.today()
date1 = now.strftime("%d/%m/%Y") # prints date in dd/mm/YY format
print("Date =", date1)
date2 = now.strftime("%d-%m-%Y") # prints date in dd-mm-YY format
print("Date =", date2)
date3 = now.strftime("%m/%d/%y") # prints date in mm/dd/yy format
print("Date =", date3)
date4 = now.strftime("%b-%d-%Y") # prints date in Mon-dd-yyyy format
print("Date =", date4)
date5 = now.strftime("%B %d, %Y") # prints date in Month dd, yyyy format
print("Date =", date5)
Run here
we have imported date class from the datetime module in the above example and then, we have used strftime()
method to format the date in desired format.
similarly you can also format date-time.
import datetime
now = datetime.datetime.now()
print (now.strftime("%d-%m-%Y %H:%M:%S")) # prints 25-04-2020 05:11:05
print (now.strftime("%d/%m/%Y")) # prints 25/04/2020
print (now.strftime("%H:%M:%S %p")) # prints 05:11:05 AM
print (now.strftime("%a, %d %b %Y")) # prints Sat, 25 Apr 2020