如何在没有dateutil的python中将时区感知字符串转换为datetime? [英] How to convert a timezone aware string to datetime in python without dateutil?

查看:148
本文介绍了如何在没有dateutil的python中将时区感知字符串转换为datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将时区感知字符串转换为python datetime对象。

I have to convert a timezone-aware string to python datetime object.

例如2012-11-01T04:16:13-04:00。

For example "2012-11-01T04:16:13-04:00".

我发现有一个 dateutil 模块有一个解析功能来做,但我真的不想使用它,因为它添加了依赖。

I find there's a dateutil module which have a parse function to do it, but I don't really want to use it as it adds a dependency.

那么我该怎么办?我已经尝试过如下,但没有运气。

So how can I do it? I have tried something like the following, but with no luck.

datetime.datetime.strptime("2012-11-01T04:16:13-04:00", "%Y-%m-%dT%H:%M:%S%Z")


推荐答案

你不能,没有很多艰苦的手动时区定义。

You can't, not without a whole lot of painstaking manual timezone defining.

Python不包含时区数据库,因为它将过时得太快。相反,Python依赖于外部库,它可以有更快的发行周期,为您提供正确配置的时区。

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

作为副作用,这意味着时区解析也需要是一个外部库。如果 dateutil 对您来说太重了,请使用 iso8601 ,它会解析你的具体格式就好了:

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 em>高达 4KB小。比较tot python-dateutil 的148KB。

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

从Python 3.2 Python 可以处理简单的基于偏移的时区,而%z 将解析 -hhmm + hhmm 时区中的时区偏移。这意味着对于ISO 8601时间戳,您必须删除时区中的

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

Python问题15873 中跟踪缺少正确的ISO 8601解析。

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

这篇关于如何在没有dateutil的python中将时区感知字符串转换为datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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