如何獲得用本機語言打印的datetime.datetime.now()
?Python中的語言環境日期格式
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
我想得到相同的結果,但用本地語言。
如何獲得用本機語言打印的datetime.datetime.now()
?Python中的語言環境日期格式
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
我想得到相同的結果,但用本地語言。
您可以只設置區域就像這個例子:
>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
sön, 23 okt 2005 20:39:15
另一種選擇是:
>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_TIME,'')
'es_CR.UTF-8'
>>> date_format = locale.nl_langinfo(locale.D_FMT)
>>> date_format
'%d/%m/%Y'
>>> today = datetime.date.today()
>>> today
datetime.date(2012, 4, 23)
>>> today.strftime(date_format)
'23/04/2012'
您應該使用%x
和%X
格式化在正確的語言環境的日期字符串。例如。在瑞典語中,日期表示爲2014-11-14
而不是11/14/2014
。
的正確方法得到的結果爲Unicode是:
locale.setlocale(locale.LC_ALL, lang)
format_ = datetime.datetime.today().strftime('%a, %x %X')
format_u = format_.decode(locale.getlocale()[1])
以下是多國語言的結果:
Bulgarian пет, 14.11.2014 г. 11:21:10 ч.
Czech pá, 14.11.2014 11:21:10
Danish fr, 14-11-2014 11:21:10
German Fr, 14.11.2014 11:21:10
Greek Παρ, 14/11/2014 11:21:10 πμ
English Fri, 11/14/2014 11:21:10 AM
Spanish vie, 14/11/2014 11:21:10
Estonian R, 14.11.2014 11:21:10
Finnish pe, 14.11.2014 11:21:10
French ven., 14/11/2014 11:21:10
Croatian pet, 14.11.2014. 11:21:10
Hungarian P, 2014.11.14. 11:21:10
Italian ven, 14/11/2014 11:21:10
Lithuanian Pn, 2014.11.14 11:21:10
Latvian pk, 2014.11.14. 11:21:10
Dutch vr, 14-11-2014 11:21:10
Norwegian fr, 14.11.2014 11:21:10
Polish Pt, 2014-11-14 11:21:10
Portuguese sex, 14/11/2014 11:21:10
Romanian V, 14.11.2014 11:21:10
Russian Пт, 14.11.2014 11:21:10
Slovak pi, 14. 11. 2014 11:21:10
Slovenian pet, 14.11.2014 11:21:10
Swedish fr, 2014-11-14 11:21:10
Turkish Cum, 14.11.2014 11:21:10
Chinese 週五, 2014/11/14 11:21:10
如果您的應用程序應該支持一個以上的區域然後讓不鼓勵通過改變區域設置(通過locale.setlocale()
)本地化的日期/時間格式。爲了解釋爲什麼這是一個壞主意看到亞歷克斯·馬爾泰利的answer的問題Using Python locale or equivalent in web applications?(基本的語言環境是全球性的,影響整個應用程序,以便更改它可能會改變應用程序的其它部分的行爲)
你可以把它乾淨用巴貝爾包像做這:
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
請參閱Date and Time在Babel的文檔中的部分。
解決俄羅斯語言和跨平臺
import sys
import locale
import datetime
if sys.platform == 'win32':
locale.setlocale(locale.LC_ALL, 'rus_rus')
else:
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
print(datetime.date.today().strftime("%B %Y"))
Ноябрь2017年
BTW它不會在Windows下運行。檢查此:http://stackoverflow.com/questions/955986/what-is-the-correct-way-to-set-pythons-locale/956084#956084 – uolot 2009-06-12 08:17:31
它還需要您運行此計算機上有地區你正在嘗試使用生成的。在GNU/Linux系統上,locale -a會給你列出可用的語言環境。在發行版之間添加新語言環境的步驟有所不同。 – 2009-06-12 08:29:43
通過**更改語言環境獲取日期/時間的本地化格式不鼓勵**。看到我的答案是正確的解決方案。 – 2017-05-04 13:12:28