Add leading zero to the hours in a date and time string

Viewed 2813

I have a variable time = "12/13/2020 7:59" and I would like to convert the string to "12/13/2020 07:59" (with leading zero before time-part).

I am not sure how to format it so that the hour has two digits.

2 Answers

You could trust the formatting options of datetime.datetime to do that for you:

from datetime import datetime

timestr = "12/13/2020 7:59"
    
dt = datetime.strptime(timestr, '%m/%d/%Y %H:%M')
corrected = datetime.strftime(dt, '%m/%d/%Y %H:%M')
    
print(corrected)
# 12/13/2020 07:59

As the doc states,

When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, [...].

So strptime accepts your text without the leading zeros, but strftime will format it properly when turning your datetime back into a string.

I enjoy using pandas pd.to_datetime() function to turn objects into proper datetime objects given it has the infer_datetime_format parameter which comes in handy and can also speed up the process too. Furthermore, with strftime you can then extract only the part you are interested in (or remove the seconds in this case):

time = '12/13/2020 7:59'
import pandas as pd
import datetime as datetime
pd.to_datetime(time,infer_datetime_format=True).strftime('%m/%d/%Y %H:%M')

Outputs:

13/12/2020 07:59
Related