Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

python - Parse datetime with hours 1-24 instead of 0-23

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...