Parsing time and time with hours 1-24 instead of 0-23

I have a data source that contains a date and time that I am reading in Python. The program always dies at the 24th hour, since python contains dates 0-23, not 1-24.

Given that I am getting a string like "2012/15/01 24", what's the best way to do this?

I could use regex to pull the date-converting to date and then re-use regex to get the hour, convert to int, subtract the hour, and then add the clock to the time date, but that seems like a pain.

Is there a better way or more general approach to this?

+2


source to share


3 answers


I'm pretty sure your data source actually has hours between 0 and 24 inclusive. Check this. It is a "silly idea" to distinguish between midnight "at the beginning of the day" and midnight "at the end of the day." If so, then, as @Amadan said, 24 actually means 00:00 the next day.

How to deal with this depends on having accurate (comprehensive) information about how the data is represented in your data source. One example is not enough to nail this. If that's all, then checking is thestring.endswith(" 24")

enough to catch this case. When you have such a case, throw out 24, convert to datetime

, then add timedelta(days=1)

to it.



Or, if you are absolutely sure that the hours range from 1 to 24 inclusive, you will have to subtract one of the hours. But I've never seen a system that works that way.

+1


source


Not mine, but he'll get the job done.



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)

      

+3


source


I would probably just go for something simple:

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

      

0


source







All Articles