Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 658
kevin wholley Avatar asked Nov 15 '25 13:11

kevin wholley


1 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.

like image 197
Thierry Lathuille Avatar answered Nov 18 '25 04:11

Thierry Lathuille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!