Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. =)

like image 521
anonymous coward Avatar asked May 27 '10 21:05

anonymous coward


People also ask

How do you remove leading zeros from a date in Python?

Your answerIf you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. This only works on Unix (Linux, OS X), not Windows. On Windows, you would use #, e.g. %Y/%#m/%#d.

How do you change time format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


2 Answers

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.

like image 58
Mike DeSimone Avatar answered Oct 04 '22 06:10

Mike DeSimone


This question has already been answered but you can technically get "2:35pm" directly from a Python datetime with .strftime("%-I:%M%P") on linux platforms that use glibc because Python's strftime() uses the c library's strftime().

>>> import datetime >>> now = datetime.datetime.now() datetime.datetime(2012, 9, 18, 15, 0, 30, 385186) >>> now.strftime("%-I:%M%P") '3:00pm' >>> datetime.time(14, 35).strftime("%-I:%M%P") '2:35pm' 

See strftime glibc notes on "-".

like image 21
Uyghur Lives Matter Avatar answered Oct 04 '22 04:10

Uyghur Lives Matter