在Python中解析datetime? [英] Parsing datetime in Python..?

查看:182
本文介绍了在Python中解析datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个系统(以Python开发),可以将 datetime作为VARIOUS格式的字符串接受,我必须解析它们。目前datetime字符串格式是: p>

I have a system (developed in Python) that accepts datetime as string in VARIOUS formats and i have to parse them..Currently datetime string formats are :

Fri Sep 25 18:09:49 -0500 2009

2008-06-29T00:42:18.000Z

2011-07-16T21:46:39Z

1294989360

现在我想要一个通用解析器,可以在适当的datetime对象中转换任何这些datetime格式...

Now i want a generic parser that can convert any of these datetime formats in appropriate datetime object...

否则我必须单独解析他们。所以请提供方法来解析它们(如果没有通用的解析器).. !!

Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!

推荐答案

as @TimPietzcker建议,dateutil包是要去的方式,它正确和自动地处理前3种格式:

As @TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:

>>> from dateutil.parser import parse
>>> parse("Fri Sep 25 18:09:49 -0500 2009")
datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))
>>> parse("2008-06-29T00:42:18.000Z")
datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())
>>> parse("2011-07-16T21:46:39Z")
datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())

unixtime格式看起来似乎很好,但幸运的是,标准的 datetime.datetime 执行任务:

The unixtime format it seems to hick up on, but luckily the standard datetime.datetime is up for the task:

>>> from datetime import datetime
>>> datetime.utcfromtimestamp(float("1294989360"))
datetime.datetime(2011, 1, 14, 7, 16)

很容易做出一个处理所有4种格式的功能:

It is rather easy to make a function out of this that handles all 4 formats:

from dateutil.parser import parse
from datetime import datetime

def parse_time(s):
    try:
        ret = parse(s)
    except ValueError:
        ret = datetime.utcfromtimestamp(s)
    return ret

这篇关于在Python中解析datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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