When I get the hour of a time, it prints it in the 24 hour clock like this;
time1 = datetime.datetime.strptime("08/Jan/2012:08:00:00", "%d/%b/%Y:%H:%M:%S")
print 'hour is ', time1.hour
> time is 8
I'm trying to get it to show 08, instead of 8. For hours that are double digits its fine, but as soon as it gets to a single digit I'm trying to get that 0 in front of it.
I could potentially do 'time1.time' and then convert to string and then split it, and then convert the hour back into a datetime object, but this is pretty long winded and was wondering if there's a simpler solution?
Just dump it back to string using .strftime()
:
>>> import datetime
>>> dt = datetime.datetime.strptime("08/Jan/2012:08:00:00", "%d/%b/%Y:%H:%M:%S")
>>> dt.hour
8
>>> dt.strftime("%H")
'08'
You cannot have leading zero for int
:
>>> type(time1.hour)
<class 'int'>
That's why you have no choice but convert time1.hour
to str
first and then manipulate the format.
You can go with @alecxe solution (which seems elegant and right) or simply use something like that:
>>> "{0:0>2}".format(time1.hour)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With