Zed
Zed

Reputation: 5931

Convert string into datime.time, error?

I am getting time data in string format like this, 'HH:MM', for example '13:33' would be 13 hours and 33 minutes.

So, I used this code to get time object and it works great

datetime.datetime.strptime('13:33', '%H:%M').time()

However, I now have new problem.New strings started coming in representing more than 24 hours and datetime.datetime.strptime('25:33', '%H:%M').time() will simply fail.What's your suggestion?

Upvotes: 2

Views: 122

Answers (3)

John Lyon
John Lyon

Reputation: 11420

A datetime.time object represents a (local) time of day, independent of any particular day.

You shouldn't use it to represent an elapsed time, like you appear to be.

More appropriate might be a datetime.timedelta:

A timedelta object represents a duration, the difference between two dates or times.

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative.

An example:

>>> from datetime import timedelta
>>> d = timedelta(hours=25,minutes=10)
>>> d
datetime.timedelta(1, 4200) #Days, seconds

Upvotes: 1

Eevee
Eevee

Reputation: 48546

You'll have to do this manually, alas.

def parse_stopwatch(s):
    hours, minutes = s.split(':', 1)
    return datetime.time(hour=int(hours), minute=int(minutes))

This is really dumb, granted. You could automatically have more than 60 minutes convert to hours, or get all fancy with a regex, or add support for days or seconds. But you'll have to be a bit more specific about where this data is coming from and what it's supposed to represent. :)

Upvotes: 0

alan
alan

Reputation: 4842

When you say "it will simply fail", I assume you want to know when it will fail. Here's one approach:

>>> import datetime
>>>
>>> time_strs = [
... "13:33",
... "25:33",
... "12:88"
... ]
>>>
>>> for s in time_strs:
...     try:
...         print datetime.datetime.strptime(s, '%H:%M').time()
...     except ValueError:
...         print "Bad time: {0}".format(s)
...
13:33:00
Bad time: 25:33
Bad time: 12:88

Upvotes: 0

Related Questions