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

后端 未结 3 1836
無奈伤痛
無奈伤痛 2020-12-21 06:28

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

相关标签:
3条回答
  • 2020-12-21 07:11

    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
    
    0 讨论(0)
  • 2020-12-21 07:14

    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)
    
    0 讨论(0)
  • 2020-12-21 07:16

    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.

    0 讨论(0)
提交回复
热议问题