Python 解析日期并找到正确的 locale_setting

Python parsing date and find the correct locale_setting

我有以下日期字符串:'3 févr. 2015 14:26:00 中欧'

datetime.datetime.strptime('03 févr. 2015 14:26:00', '%d %b %Y %H:%M:%S')

解析失败并出现错误:

ValueError: time data '03 f\xc3\xa9vr. 2015 14:26:00' does not match format '%d %b %Y %H:%M:%S'

我尝试使用 locale.locale_alias:

遍历所有语言环境
for l in locale.locale_alias:
    try:
        locale.setlocale(locale.LC_TIME, l)
        print l,datetime.datetime.strptime('03 févr. 2015 14:26:00', '%d %b %Y %H:%M:%S')
        break
    except Exception as e:
        print e

但我找不到正确的。

您的格式包含一个 作为缩写并使用 4 个字符:

'03 févr. 2015 14:26:00'
#      ^^

但是如果我将语言环境设置为 fr_FR 并设置相同的日期格式:

>>> import locale, datetime
>>> locale.setlocale(locale.LC_TIME, ('fr', 'UTF-8'))
'fr_FR.UTF-8'
>>> datetime.datetime(2015, 2, 3, 14, 26).strftime('%d %b %Y %H:%M:%S')
'03 f\xc3\xa9v 2015 14:26:00'
>>> print datetime.datetime(2015, 2, 3, 14, 26).strftime('%d %b %Y %H:%M:%S')
03 fév 2015 14:26:00

您会注意到只使用了 3 个字符,并且没有包含点。解析日期只支持相同的3字符缩写:

>>> datetime.datetime.strptime('03 fév 2015 14:26:00', '%d %b %Y %H:%M:%S')
datetime.datetime(2015, 2, 3, 14, 26)

您可以使用该工具尝试 parsedatetime library instead, others have had success parsing French dates

使用 ICU date/time format 解析本地化的 date/time 字符串:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import icu  # PyICU
import pytz # $ pip install pytz

tz = icu.ICUtzinfo.getDefault() # any ICU timezone will do here
df = icu.DateFormat.createDateTimeInstance(icu.DateFormat.MEDIUM,
                                           icu.DateFormat.MEDIUM,
                                           icu.Locale.getFrench())
df.setTimeZone(tz.timezone)

ts = df.parse(u'3 févr. 2015 14:26:00 CET') #NOTE: CET is ignored
naive_dt = datetime.fromtimestamp(ts, tz).replace(tzinfo=None)
dt = pytz.timezone('Europe/Paris').localize(naive_dt, is_dst=None)
print(dt) # -> 2015-02-03 14:26:00+01:00

df.applyPattern() 可用于设置不同的 date/time 模式 (df.toPattern()) 或者您可以 use icu.SimpleDateFormat to get df from the format and the locale directly.

有必要使用明确的 ICU 时区(以便 df.parse().fromtimestamp() 可以使用相同的 utc 偏移量)因为 icudatetime 可能使用不同的时区定义。

pytz 用于为 past/future 日期获取正确的 UTC 偏移量(某些时区在 past/future 中可能具有不同的 utc 偏移量,包括与 DST 转换无关的原因)。