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

问题描述

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

2009 年 9 月 25 日星期五 18:09:49 -05002008-06-29T00:42:18.000Z2011-07-16T21:46:39Z1294989360

现在我想要一个通用解析器,它可以将任何这些日期时间格式转换为适当的日期时间对象...

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

解决方案

正如@TimPietzcker 所建议的,dateutil 包是要走的路,它可以正确自动地处理前 3 种格式:

>>>从 dateutil.parser 导入解析>>>解析(2009 年 9 月 25 日星期五 18:09:49 -0500")datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))>>>解析(2008-06-29T00:42:18.000Z")datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())>>>解析(2011-07-16T21:46:39Z")datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())

unixtime 格式似乎有点打嗝,但幸运的是标准 datetime.datetime 可以胜任这项任务:

>>>从日期时间导入日期时间>>>datetime.utcfromtimestamp(float("1294989360"))datetime.datetime(2011, 1, 14, 7, 16)

很容易用这个函数来处理所有 4 种格式:

from dateutil.parser import parse从日期时间导入日期时间def parse_time(s):尝试:ret = 解析除了值错误:ret = datetime.utcfromtimestamp(s)返回 ret

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

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:

>>> 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:

>>> 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:

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 中解析日期时间..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:58