简体   繁体   中英

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

That can be achieved with datetime.fromisoformat() :

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

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

>>> d = datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1])
>>> 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 want pandas method try this:

sample series `s`

Out[1792]:
0    2020-01-06T00:00:00.000Z
1    2020-01-06T01:00:00.000Z
dtype: object

s_time = pd.to_datetime(s).dt.tz_localize(None)

Out[1796]:
0   2020-01-06 00:00:00
1   2020-01-06 01:00:00
dtype: datetime64[ns]

You can use python-dateutil

from dateutil import parser
parser.isoparse("2020-01-06T00:00:00.000Z")

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