简体   繁体   中英

How to convert JSON date & time to Python datetime?

I get the date and time as string like 2014-05-18T12:19:24+04:00

I found another question explaining how to handle dates in UTC timezone ( 2012-05-29T19:30:03.283Z )

What should I do with +04:00 in my case (if I want to store time in UTC timezone in Python)?

Upd . I've tried to parse it like below:

dt = '2014-05-19T14:48:50+04:00'
plus_position = dt.find('+') # remove column in the timezone part
colon_pos = dt.find(':', plus_position)
dt = dt[:colon_pos] + dt[colon_pos+1:]
dt = datetime.datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S%z') # '2014-05-19T14:48:50+0400'

But it fails - 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'

Using dateutil :

>>> import dateutil.parser
>>> dateutil.parser.parse('2014-05-18T12:19:24+04:00')
datetime.datetime(2014, 5, 18, 12, 19, 24, tzinfo=tzoffset(None, 14400))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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