正如@TimPietzcker所建议的那样,dateutil包是必经之路,它可以正确,自动地处理前三种格式:
>>> 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是该任务的标准是:
>>> from datetime import datetime>>> datetime.utcfromtimestamp(float("1294989360"))datetime.datetime(2011, 1, 14, 7, 16)
使用此函数可以轻松处理所有4种格式:
from dateutil.parser import parsefrom datetime import datetimedef parse_time(s): try: ret = parse(s) except ValueError: ret = datetime.utcfromtimestamp(s) return ret
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)