将字符串转换为datetime对象 [英] convert string to datetime object

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

问题描述

我想将此字符串转换为datetime对象:

I'd like to convert this string into a datetime object:

Wed Oct 20 16:35:44 +0000 2010

有没有一个简单的方法来做到这一点?或者我必须写一个RE来解析元素,将Oct转换为10,等等?

Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth?

编辑:
strptime是伟大的。但是,使用

strptime is great. However, with

datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y")

我得到

ValueError: 'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'

即使%z似乎是正确的。

even though %z seems to be correct.

EDIT2:
%z标签似乎不被支持。请参阅 http://bugs.python.org/issue6641
我通过使用timedelta对象来适当地修改时间,绕过它。

The %z tag appears to not be supported. See http://bugs.python.org/issue6641. I got around it by using a timedelta object to modify the time appropriately.

推荐答案

根据字符串的起源位置,您可以使用 datetime.strptime 来解析它。唯一的问题是strptime依赖某些平台特定的事情,所以如果该字符串需要能够来自任意其他系统,并且所有的日期和月份都不是完全一样的(6月或6月),你可以有麻烦。

Depending on where that string originates, you may be able to use datetime.strptime to parse it. The only problem is that strptime relies on some platform-specific things, so if that string needs to be able to come from arbitrary other systems, and all the days and months aren't defined exactly the same (Jun or June), you may have troubles.

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

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