如何用冒号解析时区 [英] How to parse timezone with colon

查看:129
本文介绍了如何用冒号解析时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 datetime.strptime 解析 +00:00格式的时区?例如:

Is there a way to parse timezone in "+00:00" format with datetime.strptime? For instance:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.strptime("12:34:56+0000", "%X%z")
datetime.datetime(1900, 1, 1, 12, 34, 56, tzinfo=datetime.timezone.utc)
>>> datetime.strptime("12:34:56+00:00", "%X%z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\lib\_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "C:\Python34\lib\_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '12:34:56+00:00' does not match format '%X%z'

有任何想法吗?

推荐答案

当前,尚无 cure ,这是和解释: https://bugs.python.org/issue15873 更准确地说,在这里: https://bugs.python.org/msg169952
但是您可以通过以下方式覆盖此问题:

Currently, there is no cure for this, and here is and explanation: https://bugs.python.org/issue15873 more precisely, here: https://bugs.python.org/msg169952 . But you can override this issue, this way:

from datetime import datetime
d = "2015-04-30T23:59:59+00:00"
if ":" == d[-3:-2]:
    d = d[:-3]+d[-2:]
print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))

这篇关于如何用冒号解析时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆