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. =)
Nothing built-in to
datetimewill do it. You’ll need to use something like:Addendum
As @naktinis points out, this is tailored to the use of this particular
strftimeparameter. Unfortunately, there is no generic solution if the content of thestrftimeparameter is unknown or unspecified (e.g. an external parameter), because it becomes a “do what I mean, not what I say” problem.Thus, given that you have to know what’s in your
strftimeparameter, in a more complex case you could solve this as parts:or with the
remodule:That said, bear in mind that if the
"%p"term gives you uppercase letters, it may be because the user set their locale to work that way, and by changing case you are overriding user preferences, which sometimes leads to bug reports. Also, the user may want something other than “am” or “pm”, such as “a.m.” and “p.m.”. Also note that these are different for different locales (e.g.en_USlocale givesAMorPMfor%p, butde_DEgivesamorpm) and you might not be getting characters in the encoding you assume.From the documentation on strftime behavior:
So, in short, if you think you need to override locale settings, make sure you have a good reason why, so you don’t just end up creating new bugs.