开发者

Format date based on locale in python

开发者 https://www.devze.com 2023-01-08 02:34 出处:网络
I have a date output like 开发者_如何学JAVA>>> import time >>> print time.strftime(\"%d %B\")

I have a date output like

开发者_如何学JAVA>>> import time
>>> print time.strftime("%d %B")
19 July

Is there a way to format the date based on the locale, but still have control of what is shown (in some cases I don't want the year).

For example, on a en_US machine, I want it to output:

July 19'th


The strftime methods always use the current locale. For example:

from datetime import date
d = date.today()
print d.format("%B %d")

will output "July 19" (no "'th", sorry...) if your locale is en_US, but "juillet 19" if the locale uses French.

If you want to make the order of the different parts also dependent on the locale, or other more advanced things, I suggest you have a look at the babel library, which uses data from the Common Locale Data Repository and allows you to do things like:

from babel.dates import dateformat
format_date(d, format="long", locale="en_US")

which would output "July 19, 2010", but "19 juillet 2010" for French, etc... Note that you have to explicitly request a specific locale though (or rather the language code) Alas, this doesn't allow leaving off the year. If you delve further into babel however, there are ways to get the patterns for a specific locale (babel.dates.get_date_format("long", locale="en_US").pattern would give you "EEEE, MMMM d, yyyy" for example, which you could use for the format argument instead of "long"). This still leaves you with the task of stripping "yyyy" out of the format, along with the comma's etc... that might come before or after. Other than that, I'm afraid you would have to make your own patterns for each locale.

0

精彩评论

暂无评论...
验证码 换一张
取 消