Reputation: 7183
I have a data source that contains datetime's I'm reading in Python. The program always dies on the 24th hour, since python holds dates 0-23 not 1-24.
Considering I get a string like '2012/15/01 24', what is the best way to handle this?
I could use regular expressions to pull out the date convert that to a date time, then use regular expressions again to get the hour, convert to an int, subtract an hour then add the hours to the datetime, but that seems like a pain.
Is there a better way, or more common approach to this?
Upvotes: 6
Views: 8786
Reputation: 142166
I'd probably just go for something simple like:
from datetime import datetime
import re
s = '2012/15/01 24'
y, d, m, h = map(int, re.findall('\d+', s))
dt = datetime(y, m, d, h - 1)
# 2012-01-15 23:00:00
Upvotes: 0
Reputation: 70602
I bet your data source actually has hours from 0 through 24 inclusive. Check that. It's a "dumb idea" to distinguish between midnight "at the start of a day" and midnight "at the end of a day". If so, then as @Amadan said, 24 really means 00:00 the next day.
How to deal with it depends on the exact (exhaustive) details of how datetimes are represented in your data source. One example isn't enough to nail that. If that's all there is to it, then checking thestring.endswith(" 24")
is sufficient to catch this case. When you do have such a case, throw the 24 away, convert to a datetime
, then add timedelta(days=1)
to it.
Or if you're absolutely sure the hours range from 1 through 24 inclusive, you'll have to subtract one from the hour. But I've certainly never seen a system that works that way.
Upvotes: 3
Reputation:
Not mine, but it'll do the job.
try:
time = datetime.datetime.strptime(time, " %H:%M:%S.%f")
except ValueError:
time = time.replace(' 24', ' 23')
time = datetime.datetime.strptime(time, " %H:%M:%S.%f")
time += datetime.timedelta(hours=1)
Upvotes: 6