本文介绍了正确解析带有时区信息的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过数据透视跟踪器API收到了这样的格式化日期字符串: 2012/06/05 17:42:29 CEST

I'm receiving a formatted date string like this via the pivotal tracker API: "2012/06/05 17:42:29 CEST"

我想将该字符串转换为UTC日期时间对象,看起来python-dateutil无法识别该时区,而pytz也不知道它。

I want to convert this string to a UTC datetime object, it looks like python-dateutil does not recognize that timezone, pytz doesn't know it either.

我担心我最好的选择是用CET替换字符串中的CEST,但这感觉非常错误。还有其他方法可以将夏令时字符串解析为我找不到的UTC日期时间对象吗?

I fear my best bet is to replace CEST in the string with CET, but this feels very wrong. Is there any other way to parse summer time strings to UTC datetime objects I couldn't find?

pytz.timezone('CEST')
# -> pytz.exceptions.UnknownTimeZoneError: 'CEST'
dateutil.parser.parse("2012/06/05 17:42:29 CEST")
# -> datetime.datetime(2012, 6, 5, 17, 42, 29)

编辑:考虑之后再次减去一小时完全是错误的,因为相应的时区也处于夏季时间,解析问题仍然存在

After thinking about it again subtracting one hour is completely false as the corresponding timezone is also currently in summer time, the issue of parsing still stands

推荐答案

没有实际的 CEST 时区。使用欧洲/巴黎欧洲/柏林欧洲/布拉格(或另一个)根据您所在的地区:

There is no real CEST timezone. Use Europe/Paris, Europe/Berlin or Europe/Prague (or another one) according to your region:

>>> pytz.country_timezones('de')
[u'Europe/Berlin']

>>> pytz.country_timezones('fr')
[u'Europe/Paris']

他们(目前)完全相同,并且在夏天都指的是 CEST

They are (currently) identical and all referring to CEST in summer.

>>> dateutil.parser.parse("2012/06/05 17:42:29 CEST").astimezone(pytz.utc)
datetime.datetime(2012, 6, 5, 15, 42, 29, tzinfo=<UTC>)

这篇关于正确解析带有时区信息的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:33