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

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

问题描述

鉴于此字符串:"Fri, 09 Apr 2010 14:10:50 +0000" 如何将其转换为 datetime 对象?

读完一些书后,我觉得这应该有效,但它没有......

<预><代码>>>>从日期时间导入日期时间>>>>>>str = '2010 年 4 月 9 日星期五 14:10:50 +0000'>>>fmt = '%a, %d %b %Y %H:%M:%S %z'>>>datetime.strptime(str, fmt)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件/usr/lib64/python2.6/_strptime.py",第 317 行,在 _strptime(bad_directive, 格式))ValueError: 'z' 是格式 '%a, %d %b %Y %H:%M:%S %z' 中的错误指令

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

<预><代码>>>>从日期时间导入日期时间>>>>>>str = '2010 年 4 月 9 日星期五 14:10:50'>>>fmt = '%a, %d %b %Y %H:%M:%S'>>>datetime.strptime(str, fmt)datetime.datetime(2010, 4, 9, 14, 10, 50)

但我坚持使用 2010 年 4 月 9 日星期五 14:10:50 +0000".我更愿意在不以任何方式更改(或切片)它的情况下完全转换它.

解决方案

看起来 strptime 并不总是支持 %z.Python 似乎只是调用 C 函数,而 strptime 在您的平台上不支持 %z.

注意:从 Python 3.2 开始,它将始终有效.

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)

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.

解决方案

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.

Note: from Python 3.2 onwards it will always work.

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

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