2

I have two strings in Python that are used to store user entered times. They are formatted as hh:mm:ss - eg 09:17:34

What is the easiest way to find the difference, in seconds, between these two times? The times will always be on the same day, so no need to worry about overlapping midnight, etc.

If I use string slicing to take out the relevant digits, then use datetime.datetime(), I can set up a datetime object for each, but I need to give it a date as well as the time I have.

I've played around with the time module, but this doesn't seem to have an easy way of working out differences in the way that using .total_seconds on a timedelta object does.

Is there any easier way?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

6

Just use datetime.datetime.strptime() directly on the two time strings; a default date (1900-01-01) is used when you are parsing just time components.

time1 = datetime.datetime.strptime(timestring1, '%H:%M:%S')
time2 = datetime.datetime.strptime(timestring2, '%H:%M:%S')
difference = time2 - time1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

You can do this with strptime:

from datetime import datetime
t1 = datetime.strptime("02:03:04", "%H:%M:%S")
t2 = datetime.strptime("05:08:06", "%H:%M:%S")
t2 - t1
# datetime.timedelta(0, 11102)
(t2 - t1).seconds
# 11102
David Robinson
  • 77,383
  • 16
  • 167
  • 187