将UTC偏移量的字符串转换为datetime对象 [英] Converting string with UTC offset to a datetime object

查看:163
本文介绍了将UTC偏移量的字符串转换为datetime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定此字符串:Fri,2010年4月9日14:10:50 +0000如何将其转换为 datetime object?

Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object?

在做了一些阅读后,我觉得这样应该可以工作,但是它不...

After doing some reading I feel like this should work, but it doesn't...

>>> from datetime import datetime
>>>
>>> str = 'Fri, 09 Apr 2010 14:10:50 +0000'
>>> fmt = '%a, %d %b %Y %H:%M:%S %z'
>>> datetime.strptime(str, fmt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'

应该注意的是,这没有问题:

It should be noted that this works without a problem:

>>> from datetime import datetime
>>>
>>> str = 'Fri, 09 Apr 2010 14:10:50'
>>> fmt = '%a, %d %b %Y %H:%M:%S'
>>> datetime.strptime(str, fmt)
datetime.datetime(2010, 4, 9, 14, 10, 50)

但我被困在Fri,09 Apr 2010 14:10:50 +0000。我更愿意以任何方式转换(或切片)它。

But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way.

推荐答案

看起来好像strptime不t始终支持%z 。 Python似乎只是调用C函数,strptime在你的平台上不支持%z

It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.

注意:从Python 3.2起,它将始终工作。

Note: from Python 3.2 onwards it will always work.

这篇关于将UTC偏移量的字符串转换为datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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