在python中处理国际日期

gee*_*jay 5 python datetime internationalization

我的日期格式为德语,例如,

2. Okt. 2009
Run Code Online (Sandbox Code Playgroud)

也许也是

2. Oct. 2009
Run Code Online (Sandbox Code Playgroud)

如何将其解析为ISO datetime(或python datetime)?

通过使用此代码段解决:

for l in locale.locale_alias:
    worked = False
    try:
        locale.setlocale(locale.LC_TIME, l)
        worked = True
    except:
        worked = False
    if worked: print l
Run Code Online (Sandbox Code Playgroud)

然后在setlocale中插入适当的参数l.

可以解析使用

import datetime
print datetime.datetime.strptime("09. Okt. 2009", "%d. %b. %Y")
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 10

http://docs.python.org/library/locale.html

datetime模块已经可以识别区域设置.

它类似于以下内容

# German locale
loc= locale.setlocale(locale.LC_TIME,("de","de"))
try:
     date= datetime.date.strptime( input, "%d. %b. %Y" )
except:
     # English locale
     loc= locale.setlocale(locale.LC_TIME,("en","us"))
     date= datetime.date.strptime( input, "%d. %b. %Y" )
Run Code Online (Sandbox Code Playgroud)

  • `type object'datetime.date'没有属性'strptime'`(2.7和3.5都没有).请改用`datetime.strptime()`. (2认同)