Python解析日期并找到正确的locale\u设置

2024-04-25 06:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的日期字符串:“3févr。2015年欧洲中部时间14:26:00

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

分析此失败,错误为:

^{pr2}$

我尝试用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

但我找不到正确的答案。在


Tags: 字符串in区域fordatetime错误时间alias
2条回答

您的格式包括缩写的,并使用4个字符:

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

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

^{pr2}$

您会注意到只使用了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)

您可以尝试使用^{} library,而其他人则使用该工具had success parsing French dates。在

要使用ICU date/time format解析本地化的日期/时间字符串:

#!/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()可用于设置不同的日期/时间模式(df.toPattern()),也可以使用use ^{} to get ^{} from the format and the locale directly。在

必须使用明确的ICU时区(这样df.parse()和{}可以使用相同的utc偏移量),因为icu和{}可能使用不同的时区定义。在

此处使用pytz,以获得过去/未来日期的正确UTC偏移量(某些时区在过去/将来可能具有不同的UTC偏移量,包括与DST转换无关的原因)。在

相关问题 更多 >