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

Question:

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!

Asked By: 1Up

||

Answers:

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

Answered By: Nilesh
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.