[英]Python converting date/time string with a timezone offset
I have something like Fri Aug 03 15:16:37 +0000 2012
and I want to convert it to 03-08-2012
. 我有类似Fri Aug 03 15:16:37 +0000 2012
东西,我想把它转换为03-08-2012
。
I also have some dates as Unix timestamp like 1344006622
, and here I am simply do: 我也有一些日期作为Unix时间戳,如1344006622
,在这里我只是做:
datetime.datetime.fromtimestamp(1344006622).strftime('%d-%m-%Y')
But this works only for the Unix timestamp. 但这仅适用于Unix时间戳。 How can I convert the first one? 我怎样才能转换第一个?
dateutil
带有dateutil
Python 2 As far as I know, Python 2 only provides a %Z
(capital Z) for timezone names , but you have an offset ( +0000
), but there is a library called dateutil that can help you: 据我所知,Python 2只为时区名称提供了%Z
(大写字母 Z),但是你有一个偏移量 ( +0000
),但是有一个名为dateutil的库可以帮助你:
>>> import dateutil
>>> import dateutil.parser
>>> dateutil.parser.parse('Fri Aug 03 15:16:37 +0000 2012')
datetime.datetime(2012, 8, 3, 15, 16, 37, tzinfo=tzutc())
In the above example I used Python 2.7.9 with dateutil 2.4.2 You can check your version with 在上面的例子中,我使用Python 2.7.9和dateutil 2.4.2你可以检查你的版本
>>> dateutil.__version__
'2.4.2'
You can install it with pip install python-dateutil
or if you want to specify a version pip install python-dateutil==2.4.2
您可以使用pip install python-dateutil
安装它,或者如果要指定版本pip install python-dateutil==2.4.2
Since Python 3.2 there is a %z
that parses the +0000
timezone info: 从Python 3.2开始,有一个%z
可以解析+0000
时区信息:
>>> from datetime import datetime
>>> datetime.strptime('Fri Aug 03 15:16:37 +0000 2012', '%a %b %d %H:%M:%S %z %Y')
datetime.datetime(2012, 8, 3, 15, 16, 37, tzinfo=datetime.timezone.utc)
For an explanation of the parameters used please refer to this table 有关所用参数的说明,请参阅此表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.