2

Im currently working on a program that will calculate the difference in hours between two time points. The variabels will always be on the same date. So what only matter is hours for me. Im planning to use datetime, but if there are other imports im open for other examples

    # This is just a ruff idea of how it should work, but im aware it doesn't work
    var1 = datetime.now().striftime('%H:%M')
    var2 = 14:55  # This is just an example

    vardiff = var2 - var1  # var2 is always bigger than var1

    print(vardiff)
Slayga
  • 23
  • 4

2 Answers2

3

There seems to be something related to your question already on

How do I find the time difference between two datetime objects in python?:

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> seconds_in_day = 24 * 60 * 60
datetime.timedelta(0, 8, 562000)
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

Based on this you can get the hours by

import datetime
first_time = datetime.datetime.strptime('12:00', '%H:%M')
later_time = datetime.datetime.now()
difference = later_time - first_time
hours, remainder = divmod(difference.seconds, 3600)
minutes,seconds=divmod(remainder,60)

there was also another helpful question/answers for time deltas: Convert a timedelta to days, hours and minutes

paloman
  • 160
  • 9
  • i just realised i forgot to mention i also wanted to know the minutes – Slayga Mar 20 '20 at 13:47
  • Hopefully you figured it already out, but if not, you can get it from the remainder: minutes,seconds=divmod(remainder,60) – paloman Mar 25 '20 at 08:08
  • i didnt have time to look at it. Had bunch other stuff i had to do so the program went on hold. I did look at it yesterday and i figured it out – Slayga Mar 25 '20 at 11:09
2

You need to compare the datetimes not the strings.

Something like

>>> import datetime
>>> t1 = datetime.datetime.strptime('03:12', '%H:%M')
>>> t2 = datetime.datetime.strptime('14:19', '%H:%M')
>>> t2 - t1
datetime.timedelta(0, 40020)
>>> print(t2 - t1)
11:07:00
Holloway
  • 6,412
  • 1
  • 26
  • 33