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

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

问题描述

因此,在Python 3中,您可以使用.isoformat()生成ISO 8601日期,但是由于Python自身的datetime指令不正确,因此您无法将isoformat()创建的字符串转换回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 Python's own datetime directives don't match properly. That is, %z = 0500 instead of 05:00 (which is produced by .isoformat()).

例如:

>>> 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-行为)

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

%z UTC偏移量,格式为+ HHMM或-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 its 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天全站免登陆