from datetime import date
d1 = date(2022, 6, 30) # Year, Month, Dayd2 = date(2023, 2, 16) # Year, Month, Daydiff_days = d2 - d1print('Difference in days :', diff_days.days) # Difference in days: 231
Getting time
import time
h = time.strftime('%I') # Getting local hour in 12-hour format as a stringh = int(h) * 2# Convert to integer and multiply by 2print(h)
Getting Date and time
from datetime import datetime
now = datetime.now()
print(now) # Present date and time# Use different formatsdt = 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 objectprint("Current Year is :", today.year) # Current year as integeryear1 = today.year# The year part or the year attributeprint("Next Year is : ", year1 + 1) # Year is an integer here.year2 = today.strftime("%Y") # Returns year as a stringprint("Previous Year is : ", int(year2) - 1) # Converts to integer then subtract