Mat*_*ner 4 python time timezone datetime pytz
如何将表单的日期时间字符串转换为Feb 25 2010, 16:19:20 CETunix时代?
目前我最好的方法是用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
Run Code Online (Sandbox Code Playgroud)
我从其他问题中看到可能会使用calendar.timegm(),以及pytz其中简化这一点,但这些不处理缩写的时区.
我想要一个需要最少多余库的解决方案,我希望尽可能多地保留标准库.
Python标准库并没有真正实现时区.你应该用python-dateutil.它为标准datetime模块提供了有用的扩展,包括时区实现和解析器.
您可以将时区感知datetime对象转换为UTC .astimezone(dateutil.tz.tzutc()).对于当前时间作为时区感知日期时间对象,您可以使用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'))
Run Code Online (Sandbox Code Playgroud)
不幸的是,在重复的夏令时期间,这种技术将是错误的.
| 归档时间: |
|
| 查看次数: |
7534 次 |
| 最近记录: |