from datetime import date
dt = date.today()
print(dt) # 2019-09-16
Python date and time to get todays tomorrow yesterday dates by using relative delta for calculations
Getting day , month , year and weekday
Commonly used instances
from datetime import date
print("Today day : ",date.today().day)
print("Today month : ",date.today().month)
print("Today year : ",date.today().year)
print("Today weekday : ",date.today().weekday())
Output
Today day : 16
Today month : 9
Today year : 2019
Today weekday : 0
from datetime import date
d1 = date(2022, 6, 30) # Year , Month , day
d2 = date(2023, 2, 16) # Year , Month , day
diff_days = d2 - d1
print('Difference in days :',diff_days.days) # Difference in days : 231
Getting time
import time
h=time.strftime('%I') # getting local hour in 12 hours format as string
h=int(h)*2 # to multiply the hour as integer
print (h)
Getting Date and time
from datetime import datetime
now = datetime.now()
print(now) # present date and time
# use different formats
dt=datetime.strftime(now,'%Y/%m/%d : %H:%M:%S')
print(dt)
The function strftime() returns string, so we have to convert the output to integer if we are doing any calculation using the output. Note the last line here.
import datetime
today = datetime.datetime.now() # creating date object
print("Current Year is :",today.year) # Current year as integer
year1 = today.year #The year part or the year attribute
print("Next Year is : ", year1+1) # Year is an integer here.
year2 = today.strftime("%Y") # Returns year as a string
print("Previous Year is : ",int(year2)-1) # converts to integer then subtract