如何在python中将字符串'2020-01-06T00:00:00.000Z'转换为datetime?

时间:2020-01-15 02:58:02

标签: python pandas datetime

正如问题所述,我有一系列的字符串,例如'2020-01-06T00:00:00.000Z'。如何使用Python将本系列转换为datetime?首选熊猫方法。如果没有,有什么方法可以解决这个任务?谢谢。

string '2020-01-06T00:00:00.000Z' 
convert to 2020-01-06 00:00:00 under datetime object

3 个答案:

答案 0 :(得分:4)

可以通过datetime.fromisoformat()实现:

Python 3.7.6 (default, Dec 19 2019, 22:52:49) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1])
datetime.datetime(2020, 1, 6, 0, 0)
>>> 

要将其格式化为%Y-%m-%d %H:%M:%S,可以执行以下操作:

>>> d = datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1])
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2020-01-06 00:00:00'
>>>

答案 1 :(得分:2)

给出raw_time是包含字符串时间的列。你可以做到

pd.to_datetime(df['raw_time'])

答案 2 :(得分:1)

如果要使用熊猫方法,请尝试以下操作:

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]