Search code examples
python-3.xpandaspython-datetime

Pandas strftime with 24 hour format


QUESTION

How can I convert 24 hour time to 12 hour time, when the time provided is two characters long? For example: How to format 45 as 12:45 AM.

ATTEMPT

I can get most of the time conversions to format properly with the following:

df=df.assign(newtime=pd.to_datetime(df['Time Occurred'], format='%H%M').dt.strftime("%I:%M %p"))
df.head()

Date Reported   Date Occurred  Time Occurred    newtime
9/13/2010       9/12/2010       45          4:05 AM
8/9/2010        8/9/2010        1515        3:15 PM
1/8/2010        1/7/2010        2005        8:05 PM
1/9/2010        1/6/2010        2100        9:00 PM
1/15/2010       1/15/2010       245         2:45 AM

In the above the values in newtime are properly formatted, except where in the input time is "45" - that time had the result 4:05 AM. Does anyone know how to create the proper output?


Solution

  • to_datetime

    times = pd.to_datetime([
        f'{h:02d}:{m:02d}:00' for h, m in zip(*df['Time Occurred'].astype(int).__divmod__(100))
    ])
    df.assign(newtime=times.strftime('%I:%M %p'))
    
       Time Occurred   newtime
    0             45  12:45 AM
    1           1515  03:15 PM
    2           2005  08:05 PM
    3           2100  09:00 PM
    4            245  02:45 AM