How can i get current date and time in Python?


Which module we can use to get date and time in Python?

1 Answer

5 years ago by

Use now() function of datetime python module to get current date and time.

For example, we have imported datetime class in the below example and then, we have used datetime.datetime.now() method to get the current local date-time.

import datetime

now = datetime.datetime.now() 
print (str(now)) # prints 2020-04-25 05:04:21.659405

strftime() method is used to format datetime in your desired format as shown below:

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
5 years ago by Divya