如何将格式为 Feb 25 2010, 16:19:20 CET
的日期时间字符串转换为 unix 纪元?
目前我最好的方法是使用 time.strptime()
是这样的:
def to_unixepoch(s):
# ignore the time zone in strptime
a = s.split()
b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z")
# this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME)
c = int(time.mktime(b))
# UTC+TZ
c -= time.timezone
# UTC
c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]]
return c
我从其他问题中看到,可以使用 calendar.timegm()
和 pytz
等来简化这个问题,但这些并不能处理缩写时区。
我想要一个需要最少多余库的解决方案,我喜欢尽可能多地使用标准库。
Python 标准库并没有真正实现时区。你应该使用 python-dateutil
.它为标准 datetime
模块提供了有用的扩展,包括时区实现和解析器。
您可以使用 .astimezone(dateutil.tz.tzutc())
将时区感知 datetime
对象转换为 UTC。对于作为时区感知日期时间对象的当前时间,您可以使用 datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
。
import dateutil.tz
cet = dateutil.tz.gettz('CET')
cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)
cesttime.isoformat()
'2010-04-01T12:57:00+02:00'
cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)
cettime.isoformat()
'2010-01-01T12:57:00+01:00'
# does not automatically parse the time zone portion
dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\
.replace(tzinfo=dateutil.tz.gettz('CET'))
不幸的是,这种技术在重复的夏令时期间会出错。