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
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'
>>>
Given raw_time
is column contains the string time. You can do this
pd.to_datetime(df['raw_time'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With