Skip to main content
 首页 » 编程设计

python之解决 time.strptime(today.strftime ("%x"), "%x") 在某些地区失败

2025年05月04日9bjzhanghao

尝试在文本图形用户界面小部件中显示本地化日期字符串。我目前采用的方法是将带有 datetime.datetime.strftime("%x") 的本地化字符串显示到文本小部件中,以便用户可以对其进行编辑。然后我尝试用 time.strptime("x") 解析字符串。

目前的问题是对于某些地区(or_IN, ja_JP.UTF-8, ko_KO.UTF-8)time.strptime("x") 无法解析datetime.datetime.strftime("% X”)。 它总是抛出一个 ValueError 试图解析它。

我怀疑这是在日期格式中使用双字节分隔符的 strptime 和日期字符串的问题。这也可能是 %x 对 strftime 和 strptime 的意义不同的问题(如果我理解正确,一个基本上只是 glibc 实现,而另一个是特定于 python 的)。

我正在寻找一种更好的方法来处理本地化的日期字符串,以便可以在用户界面中对其进行编辑。

#!/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 

请您参考如下方法:

检查locale_alias字典中是否有您的语言环境

>>> import locale 
>>> len(locale.locale_alias) 
843 
>>> locale.locale_alias.keys()[:10] 
['ko_kr.euc', 'is_is', 'ja_jp.mscode', 'kw_gb@euro', 'yi_us.cp1255', 'ca_es@euro', 'ja_jp.ujis', 'ar_ma', 'greek.iso88597', 'sr_yu.iso88592'] 
>>>