简体   繁体   English

在 Python 中解析日期时间..?

[英]Parsing datetime in Python..?

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 :我有一个系统(用 Python 开发)接受日期时间作为各种格式的字符串,我必须解析它们..目前日期时间字符串格式是:

Fri Sep 25 18:09:49 -0500 2009

2008-06-29T00:42:18.000Z

2011-07-16T21:46:39Z

1294989360

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 suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:正如@TimPietzcker 建议的那样, dateutil 包是要走的路,它可以正确自动地处理前 3 种格式:

>>> 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())

The unixtime format it seems to hiccough on, but luckily the standard datetime.datetime is up for the task: unixtime 格式似乎有点打嗝,但幸运的是标准的datetime.datetime可以完成任务:

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

It is rather easy to make a function out of this that handles all 4 formats:很容易用这个函数来处理所有 4 种格式:

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

您应该查看dateutil包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM