user2448592
user2448592

Reputation: 101

Python - convert elapsed time to seconds when format is not consistent

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?

Upvotes: 1

Views: 578

Answers (1)

grasshopper
grasshopper

Reputation: 4068

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

Upvotes: 1

Related Questions