python


Current date and time

We will use the date class of the datetime module, although we can also use datetime.datetime.today() but it will give date with time.


from datetime import date

today = date.today()
print("Today's date:", today)
                
Output:

Today's date: 2020-08-01
                

Getting current date and time


from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string) 
            
Output

now = 2020-08-01 15:23:02.486023
date and time = 01/08/2020 15:23:02
            

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.