Nothing built-in to datetime
will do it. You'll need to use something like:
datetime.time(1).strftime('%I:%M%p').lstrip('0')
Addendum
As @naktinis points out, this is tailored to the use of this particular strftime
parameter. Unfortunately, there is no generic solution if the content of the strftime
parameter 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 strftime
parameter, in a more complex case you could solve this as parts:
tval = datetime.time(1)
tval_str = (tval.strftime('%A, %B ') + tval.strftime('%d').lstrip('0')
+ tval.strftime(' %Y, ') + tval.strftime('%I:%M').lstrip('0')
+ tval.strftime('%p').lower())
or with the re
module:
tval = datetime.time(1)
tval_str = re.sub(r"^0|(?<=\s)0", "",
re.sub(r"(?<=[0-9])[AP]M", lambda m: m.group().lower(),
tval.strftime('%A, %B %d %Y, %I:%M%p')))
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_US
locale gives AM
or PM
for %p
, but de_DE
gives am
or pm
) and you might not be getting characters in the encoding you assume.
From the documentation on strftime behavior:
Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain Unicode characters encoded using the locale’s default encoding (for example, if the current locale is js_JP
, the default encoding could be any one of eucJP
, SJIS
, or utf-8
; use locale.getlocale()
to determine the current locale’s encoding).
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.