Alex Rivera | Logout

Get "2:35pm" instead of "02:35PM" from Python date/time?

Asked 2010-05-27T21:48:08.913
29

I'm still a bit slow with Python, so I haven't got this figured out beyond what's obviously in the docs, etc.

I've worked with Django a bit, where they've added some datetime formatting options via template tags, but in regular python code how can I get the 12-hour hour without a leading zero?

Is there a straightforward way to do this? I'm looking at the 2.5 and 2.6 docs for "strftime()" and there doesn't seem to be a formatting option there for this case.

Should I be using something else?

Feel free to include any other time-formatting tips that aren't obvious from the docs. =)

Edit
Report

2 Answers

2

Use %l to get the hour as a number between 1..12:

In [2]: datetime.time(hour=14,minute=35).strftime('%l:%M%p')
Out[2]: ' 2:35PM'

For more format codes, see https://www.php.net/strftime.

answered 2010-05-28T00:39:06.897
0

A little hack that I've used:

# a time object
mytime = time(hour=time_hour, minute=time_minute)
# return a time as a string without a leading zero in hours.
return "%s:%s" % (mytime.hour, mytime.strftime("%M"))
answered 2011-10-23T21:14:36.123

Your Answer