1

I am trying to identify the number of seconds that have elapsed given a time string. These time strings are not always consistent.

Examples:

'01:02' = 1 minute, 2 seconds = 62 seconds

'1-11:01:02' = 1 day, 11 hours, 1 minute, 2 seconds = 126062 seconds

I have tried time.strptime, but I didn't see a way to elegantly perform this operation. Any ideas?

user2448592
  • 101
  • 1
  • 8

1 Answers1

1

One way to go about it is to gather all possible formats in an array and check the time_str against them:

 time_formats = ["%m-%d:%H:%M","%H:%M"]
 time_val = None

 for fmt in time_formats:
    try:
      time_val = time.strptime(time_str,fmt)
    except:
      pass

 if time_val is None:
      print "No matching format found"

This try-catch structure is consistent with the EAFP principle in python. http://docs.python.org/2/glossary.html

grasshopper
  • 3,988
  • 3
  • 23
  • 29
  • does it make sense to represent *elapsed time* as `time.struct_time()`? `datetime.timedelta()` could be used instead – jfs Mar 19 '14 at 16:24
  • problem is, timedelta doesn't have this strptime capability. One can convert between these different formats as described in the answers of this question: http://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object – grasshopper Mar 19 '14 at 16:29