从字符串中获取已知的日期时间对象
有没有一种方法可以仅使用标准库模块从 Python 中的字符串中获取日期时间感知对象?
我知道我可以使用 dateutil.parser.parse,但不幸的是,这并不是将其作为依赖项添加到我的项目的充分理由。我已经将 mx.DateTime 模块作为依赖项,但是:
>>> dateutil.parser.parse('2011-10-24T06:51:47-07:00')
datetime.datetime(2011, 10, 24, 6, 51, 47, tzinfo=tzoffset(None, -25200))
>>> mx.DateTime.ISO.ParseDateTimeUTC('2011-10-24T06:51:47-07:00')
<mx.DateTime.DateTime object for '2011-10-24 13:51:47.00' at 29c7e48>
ParseDateTimeUTC 无法检测偏移量,尽管在其文档中指出:
Returns a DateTime instance in UTC reflecting the given ISO
date. A time part is optional and must be delimited from the
date by a space or 'T'. Timezones are honored.
Is there a way I can obtain a datetime aware object out of a string in Python using only the standard library modules ?
I know that I can use dateutil.parser.parse
, but unfortunately that's not a good enough reason to add it as a dependency to my project. I already have the mx.DateTime
module as a dependency, buuttttt:
>>> dateutil.parser.parse('2011-10-24T06:51:47-07:00')
datetime.datetime(2011, 10, 24, 6, 51, 47, tzinfo=tzoffset(None, -25200))
>>> mx.DateTime.ISO.ParseDateTimeUTC('2011-10-24T06:51:47-07:00')
<mx.DateTime.DateTime object for '2011-10-24 13:51:47.00' at 29c7e48>
the ParseDateTimeUTC
fails to detect the offset, even though in its documentation says that:
Returns a DateTime instance in UTC reflecting the given ISO
date. A time part is optional and must be delimited from the
date by a space or 'T'. Timezones are honored.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
mx.DateTime.ISO.ParseDateTimeUTC
正在做正确的事情 - 它正在应用指定的时区来将时间调整为 UTC。生成的 UTC 时间没有时区,因为它不再是本地时间。标准 Python 库不包含任何具体时区类 根据文档:
我一直很惊讶它们至少没有包含 UTC 类,或者像 dateutil 的
tzoffset
这样的通用实现。mx.DateTime.ISO.ParseDateTimeUTC
is doing the right thing - it is applying the specified timezone to adjust the time to UTC. The resulting UTC time doesn't have a timezone because it isn't a local time anymore.The standard Python library doesn't contain any concrete timezone classes according to the documentation:
I've always been surprised that they didn't at least include a class for UTC, or a generic implementation like dateutil's
tzoffset
.