LA_
LA_

Reputation: 20409

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'

Upvotes: 2

Views: 4249

Answers (1)

falsetru
falsetru

Reputation: 368954

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

Upvotes: 3

Related Questions