Convert a timezone aware string to datetime python which is in format like '2012-11-01T04:16:13.000Z'

Viewed 898

I have stumbled upon a coding question where I have to convert a timezone-aware string like 2021-11-01T02:08:13.000Z to a Python datetime object.

I have seen many examples where timezone aware string is like in the format 2012-11-01T04:16:13-04:00, but for me as you can see the string is little different with the ".000Z" at the end.

I tried the below code:

from datetime import datetime

format = '%Y-%m-%dT%H:%M:%S%z'
time='2012-11-01T04:16:13.000Z'
date_time_obj = datetime.strptime(time, format)
print ("date",date_time_obj)

But I'm getting the error:

ValueError: time data '2012-11-01T04:16:13.000Z' does not match format '%Y-%m-%dT%H:%M:%S%z'

also tried doing like this:

from datetime import datetime
time='2012-11-01T04:16:13.000Z'
date_time_obj = datetime.fromisoformat(time)

But I'm getting this error:

Errpr: Invalid ISO format string:

I gone through many pages but was unable to find that particular format and how to convert it to a datetime aware string. Can anyone please help.

2 Answers

You can do all of this using 'dateutil.parser.isoparse'. No need to strip out information (dropping the milliseconds), no need to fuss with the formatting string.

from dateutil import parser
time='2012-11-01T04:16:13.000Z'
date_time_obj = parser.isoparse(time)
print ("date",date_time_obj)

> date 2012-11-01 04:16:13+00:00

You may change your format like this:

format = '%Y-%m-%d %H:%M:%S'

And convert time like you format by doing this:

time='2012-11-01T04:16:13.000Z'
time=time.replace("T"," ").split(".")[0]

Or you may format it like

format = '%Y-%m-%dT%H:%M:%S.%f'

And you don't have to do anything for time now.

time='2012-11-01T04:16:13.000Z'
Related