Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime get the hour in 2 digit format [duplicate]

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?

like image 285
user1165419 Avatar asked Jun 17 '16 16:06

user1165419


2 Answers

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'
like image 109
alecxe Avatar answered Nov 20 '22 04:11

alecxe


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)
like image 36
vrs Avatar answered Nov 20 '22 05:11

vrs