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'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
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)
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.