如何将python.isoformat()字符串转换回datetime对象 [英] How to convert python .isoformat() string back into datetime object

查看:5302
本文介绍了如何将python.isoformat()字符串转换回datetime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在Python 3中,您可以使用.isoformat()生成ISO 8601日期,但是不能将由isoformat()创建的字符串转换回datetime对象,因为pythons拥有的datetime伪指令不正确。即:%z = 0500而不是05:00(由.isoformat()生成)。
例如:

So in Python 3, you can generate an ISO 8601 date with .isoformat() , but you can't convert a string created by isoformat() back into a datetime object because pythons own datetime directives don't match properly. ie: %z = 0500 instead of 05:00 (which is produced by .isoformat() ). For example:

>>> strDate = d.isoformat()
>>> strDate
'2015-02-04T20:55:08.914461+00:00'

>>> objDate = datetime.strptime(strDate,"%Y-%m-%dT%H:%M:%S.%f%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 '2015-02-04T20:55:08.914461+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

从Python的strptime文档:( https://docs.python.org /2/library/datetime.html#strftime-strptime-behavior

From Python's strptime documentation: (https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior)


%z + HHMM格式的UTC偏移量或-HHMM(空字符串,如果
对象是天真的)。 (空),+0000,-0400,+1030

%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). (empty), +0000, -0400, +1030

所以简而言之,Python甚至不遵守自己的字符串格式化指令

So, in short Python does not even adhere to it's own string formatting directives.

我知道datetime在python中已经是可怕的,但这真的超越了无理的平凡的愚蠢之地。

I know datetime is already terrible in python but this really goes beyond unreasonable into the land of plain stupidity.

告诉我这是不正确的。

推荐答案

事实证明,这是这个问题当前最好的解决方案 :

As it turns out this is the current best "solution" to this question:

pip install python-dateutil

然后...

import datetime
import dateutil.parser

def getDateTimeFromISO8601String(s):
    d = dateutil.parser.parse(s)
    return d

这篇关于如何将python.isoformat()字符串转换回datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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