Date difference

  Uncategorized
date difference: example 1:

def dd(date1,date2):
    d1 = datetime.strptime(date1,'%m/%d/%y')
    d2 = datetime.strptime(date2,'%m/%d/%y')
    diffDays = (d1-d2).days
    return diffDays
example 2:

from datetime import datetime, timedelta 

ini_time_for_now = datetime.now() 
future_date_after_2yrs = ini_time_for_now + timedelta(days = 730) 
future_date_after_2days = ini_time_for_now + timedelta(days = 2)

past_date_before_2yrs = ini_time_for_now - timedelta(days = 730) 
past_date_before_2hours = ini_time_for_now - timedelta(hours = 2) 

new_final_time = ini_time_for_now + timedelta(days = 2) 
print('Time difference:', str(new_final_time - ini_time_for_now)) 
example 3:

import datetime 
d1 = datetime.datetime(2020, 4, 26, 9, 0, 1) 
d2 = datetime.datetime(2021, 10, 21, 1, 3, 45)
d12=d1-d2
print(d12.days)
print(d12.seconds // 3600)  #hours
print(d12.seconds // 60 % 60)  #minutes
print(d12.seconds)
example 4: total different hours

import datetime 
d1 = datetime.datetime(2020, 4, 26, 9, 0, 1) 
d2 = datetime.datetime(2021, 10, 21, 1, 3, 45)
d12=d1-d2

totsec = d12.total_seconds()
h = totsec//3600
m = (totsec%3600) // 60
sec =(totsec%3600)%60 #just for reference
print("%d:%d" %(h,m))

Python DateTime, TimeDelta, Strftime(Format) with Examples
Timedelta function demonstration