沒有試圖顯示文本GUI窗口小部件本地化的日期字符串。我現在採用的方法是將帶有datetime.datetime.strftime(「%x」)的本地化字符串顯示到文本小部件中,以便用戶可以對其進行編輯。然後我嘗試用time.strptime(「x」)解析字符串。 (or_IN,ja_JP.UTF-8,ko_KO.UTF-8)time.strptime(「x」)無法解析由datetime.datetime.strftime(「x」)生成的格式,因此無法解析datetime.datetime.strftime %X」)。 它總是拋出一個ValueError試圖解析這個。工作周圍time.strptime(today.strftime(「%X」),「%X」)在某些地區
我懷疑這是與在日期格式使用雙字節分隔符strptime和日期字符串的一個問題。對於strftime和strptime的%x方式(如果我理解正確,一個基本上只是glibc實現,而另一個是python特定的),它可能也是一個問題。
我在尋找一個更好的方法來處理本地化的日期字符串,使他們可以在UI中進行編輯。
#!/usr/bin/python
# We are trying to present a localized date in a text widget, so
# that a user could potentially edit it, and then we try to
# parse it with datetime.strptime
# however, even if the user doesn't edit the date produced
# by today.strftime("%x"), time.strptime(DATE, "%x") fails
# to parse it
# Not sure what's going on there before. I've seen this once
# before with in_OR, and that turned out to be a locale bug
# in glibc. This could also be the case, so what I'm looking
# for is a more robust approach to this problem that will
# work on all locales
# platform: fedora 14, x86_64
# Python 2.7 (r27:82500, Sep 16 2010, 18:02:00)
# [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
import datetime
import time
import locale
today = datetime.date.today()
# works for "C"
locale.setlocale(locale.LC_ALL, 'C')
print time.strptime(today.strftime("%x"), "%x")
# works for en_us.utf8
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
print time.strptime(today.strftime("%x"), "%x")
# fails for 'ja_JP.UTF-8'
loc = 'ja_JP.UTF-8'
locale.setlocale(locale.LC_ALL,loc)
try:
print today.strftime("%x")
print time.strptime(today.strftime("%x"), "%x")
except ValueError:
print "failed for %s" % loc
loc = 'ko_KR.UTF-8'
locale.setlocale(locale.LC_ALL,loc)
try:
print today.strftime("%x")
print time.strptime(today.strftime("%x"), "%x")
except ValueError:
print "failed for %s" % loc
而且這個測試程序的我的系統(Fedora 14的,x86_64的)對樣本輸出:
time.struct_time(tm_year=2011, tm_mon=10, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=283, tm_isdst=-1)
time.struct_time(tm_year=2011, tm_mon=10, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=283, tm_isdst=-1)
2011年10月10日
failed for ja_JP.UTF-8
2011년 10월 10일
failed for ko_KR.UTF-8
Ja_JP表示/ ko_kr似乎是在那裏(在locale.locale_encoding_alias UTF8)。我不確定這裏的含義是什麼。 locale似乎被正確設置,並且LC_ *似乎是正確的,並且strftime(「%x」)似乎做正確的事情(好,看起來做得正確,它匹配「LANG = ja_JP.UTF-例如,8日期'+%x'「。 – alikins