3

I am working with an API that is returning a JSON string that contains the following date/time in it:

2013-03-14T14:15:23-07:00

I get the date and the time, down to the second. But the last 5 characters are confusing me. I'm guessing that's a UTC offset. (mountain time) What i can't figure out how to do is to compare the above string to a date/time in python. The T is also throwing me off.

How do I encode a python date/time string to match the above?

4

2 回答 2

3

如果您使用该python-dateutil库(https://crate.io/packages/python-dateutil/),您可以将该值转换为datetime.

>>> dateutil.parser.parse('2013-03-14T14:15:23-07:00')
datetime.datetime(2013, 3, 14, 14, 15, 23, tzinfo=tzoffset(None, -25200))
于 2013-02-13T05:36:45.773 回答
2

您正在查看ISO 8601日期格式。您可以使用包来解析它或自己做。

您可以使用 datetime.strptime 来解析:

>>> ts='2013-03-14T14:15:23-07:00'
>>> datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S')
datetime.datetime(2013, 3, 14, 14, 15, 23)

然后只需添加/减去时间增量(对于“天真”对象):

>>> datetime.timedelta(hours=int(ts[-6:-3]))
datetime.timedelta(-1, 61200)

所以:

>>> d=datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S')+datetime.timedelta(hours=int(ts[-6:-3]))
>>> d
datetime.datetime(2013, 3, 14, 7, 15, 23)

棘手的部分是 TZ 是可选的,无论您是添加/减去时间偏移还是在日期对象中设置时区。

于 2013-02-13T05:52:48.867 回答