Finding total hours between two dates in Python

  • In python, if we try the difference between 2 datetime objects, result will be the number of days between the 2 dates plus the extra seconds.
    Using this we can find the number of hours, minutes or seconds between the dates given.
    Sample below.

    Copied
    import datetime
    
    startdate = datetime.datetime(2022, 1, 1, 14, 00, 00)
    enddate = datetime.datetime(2022, 1, 2, 15, 10, 30)
    
    difference = (enddate - startdate)
    
    totalhours = (difference.days * 24) + (difference.seconds // 3600)
    print(totalhours)
    
    totalminutes = (difference.days * 24 * 60) + (difference.seconds // 60)
    print(totalminutes)
    
    totalseconds = (difference.days * 24 * 60 * 60) + difference.seconds
    print(totalseconds)
    
    Output:
      25
      1510
      90630
  • For dates in string format, convert to the datetime objects and then find the difference.

    Copied
    import datetime
    
    sdt = '2022/2/1'
    edt = '2022/2/28'
    
    startdate = datetime.datetime.strptime(sdt, '%Y/%m/%d')
    enddate = datetime.datetime.strptime(edt, '%Y/%m/%d')
    
    dt = startdate
    sundaylist = []
    while dt < enddate:
        weekday = int(dt.strftime('%w'))
        if (weekday == 0): #Sunday
            sundaylist.append(dt)
        dt += datetime.timedelta(days=1)
    
    stringdates = [ datetime.datetime.strftime(d, '%Y/%m/%d') for d in sundaylist]
    print(stringdates)
    
    Output:
      50
      3010
      180610
Absolute Code Works - Python Topics