Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert the string '2020-01-06T00:00:00.000Z' into a datetime object?

As the question says, I have a series of strings like '2020-01-06T00:00:00.000Z'. How can I convert this series to datetime using Python? I prefer the method on pandas. If not is there any method to solve this task? Thank all.

string '2020-01-06T00:00:00.000Z' 
convert to 2020-01-06 00:00:00 under datetime object
like image 222
ShanN Avatar asked Jan 15 '20 02:01

ShanN


2 Answers

With Python 3.7+, that can be achieved with datetime.fromisoformat() and some tweaking of the source string:

>>> from datetime import datetime
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1] + '+00:00')
datetime.datetime(2020, 1, 6, 0, 0, tzinfo=datetime.timezone.utc)
>>> 

And here is a more Pythonic way to achieve the same result:

>>> from datetime import datetime
>>> from datetime import timezone
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
datetime.datetime(2020, 1, 6, 3, 0, tzinfo=datetime.timezone.utc)
>>> 

Finally, to format it as %Y-%m-%d %H:%M:%S, you can do:

>>> d = datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2020-01-06 00:00:00'
>>>
like image 63
accdias Avatar answered Jan 05 '23 00:01

accdias


Given raw_time is column contains the string time. You can do this

pd.to_datetime(df['raw_time'])
like image 25
hunzter Avatar answered Jan 04 '23 23:01

hunzter