-1

I would like to calculate the time difference between two 24-hour time values, containing only the hour, minute, and second values. Then, I would like to split up the time difference into the hour, minute, and seconds values, and output them as three different variables.

For example, my desired output would be:

time1 = '10:33:26'
time2 = '17:25:39'

Hours: 6
Minutes: 52
Seconds: 13

Because 17:25:39 is 6 hours, 52 minutes, and 13 seconds after 10:33:26.

I have tried the following code:

from datetime import datetime

s1 = '10:33:26'
s2 = '17:25:39'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print(tdelta)

It correctly outputs 6:52:13, but I don't know how to split up the 6, 52, and 13 into three different variables.

Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
  • 1
    Use `str(tdelta).split(":")` directly. – jizhihaoSAMA Aug 11 '20 at 05:03
  • I think that probably working with the numeric value `tdelta.total_seconds()` and doing the calculations is going to be more robust. The `str(tdelta)` is intended to be human-readable rather than for machine parsing. – alani Aug 11 '20 at 05:06
  • Does this answer your question? [Difference between two dates in Python](https://stackoverflow.com/questions/8419564/difference-between-two-dates-in-python) & [How to extract hours and minutes from a datetime.datetime object?](https://stackoverflow.com/questions/25754405) & [Calculating Time Difference](https://stackoverflow.com/questions/3426870/) – Trenton McKinney Aug 11 '20 at 05:18
  • [How to calculate the time interval between two time strings](https://stackoverflow.com/questions/3096953) – Trenton McKinney Aug 11 '20 at 05:31

3 Answers3

3

You probably want to do the numeric calculation yourself directly from the total_seconds(), rather than relying on back-parsing the result of the string conversion (intended for human-readable output). For example:

from datetime import datetime

s1 = '10:33:26'
s2 = '17:25:39'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

ts = int(tdelta.total_seconds())
secs = ts % 60
mins = (ts // 60) % 60
hours = (ts // 3600)

print(hours, mins, secs)
alani
  • 12,573
  • 2
  • 13
  • 23
0

You can convert the output to a string and then use the split() method. For example:

str(tdelta).split(':')

Will output:

['6', '52', '13']

Then you can simply loop through the outputted list.

ChaddRobertson
  • 605
  • 3
  • 11
  • 30
0

You can perform numeric computation by using timedelta.

time1 = datetime.timedelta(hours=10, minutes=33,seconds=26)
time2 = datetime.timedelta(hours=17, minutes=25,seconds=39)

time_diff = time2 - time1

hour, min, sec = str(time_diff ).split(':')

print(hour, min, sec)

awadhesh pathak
  • 121
  • 1
  • 4