10

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?

user1165419
  • 663
  • 2
  • 10
  • 21

2 Answers2

12

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'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

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)
vrs
  • 1,922
  • 16
  • 23
  • 5
    Why use `>`? If you use `{0:02d}` instead, then the `=` format is implied and you get sign handling for free. See the [format spec](https://docs.python.org/2/library/string.html#formatspec). – Martijn Pieters Jun 17 '16 at 16:56