ValueError: time data '24:00' does not match format '%H:%M'

梦想的初衷 提交于 2019-12-10 10:43:49

问题


I'm having serious trouble converting 24 hour time to 12 hour.

def standard_time(t):     
    t = datetime.strptime(t, "%H:%M")
    return t

When fed in '24:00' we get

ValueError: time data '24:00' does not match format '%H:%M'

I also attempt converting using %I (12 hour) instead of %H, but get an error whenever hours go over 12:

def standard_time(t):     
    t = datetime.strptime(t, "%I:%M")
    return t

Sort of stuck...

ValueError: time data '13:30' does not match format '%I:%M'

Does python have a simple 24 hour to 12 hour converter? Ideally 23:00 should put out 11:00 PM and 24:00 should not throw an error!


回答1:


You have to give 00:00 for 24:00. Last count in 24 hour format is 23:59 after that next value will be 00:00.

Like if you have 23:59, and add one more minutes in that

>>> a = datetime(1900, 1, 1, 23, 59)
>>> from datetime import timedelta
>>> a + timedelta(minutes=1)
datetime.datetime(1900, 1, 2, 0, 0)

You will get next date with 00:00



来源:https://stackoverflow.com/questions/25132870/valueerror-time-data-2400-does-not-match-format-hm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!