如何将形式为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
等工具来简化此过程,但这些工具不能处理缩写的时区。
我想要一种需要最少额外库的解决方案,尽可能使用标准库。