Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...