他们将字符串转换为 DateTime (python) 的最快速度是多少?

What is the fastest they to convert string to DateTime (python)?

我有一个包含 iddate 列的数据框,日期是 string:

df = pd.DataFrame([[0, '2020-03-26T15:37:19.765000Z'], [1, '2019-03-25T15:37:18Z'], [2, '2020-03-26T15:37:19.765000Z']], columns = ['id', 'date'])

我必须将日期转换为 DateTime 才能进一步工作。我只能找到一种解决方案,使用 for 循环。

for i in range(len(df)):
    if (len(df.loc[i, 'date']) != 27): 
       df.loc[i, 'date'] = df.date[i].replace('Z', '.000000Z')

for i in range(len(df)):
    df.loc[i, 'date'] = datetime.strptime(str(df.date[i]), '%Y-%m-%dT%H:%M:%S.%fZ')

它按我的需要工作,但如果 df 很大,它就会慢得令人无法接受。 有什么建议吗?

因为您正在使用 pandas,所以您可以使用 to_datetime() 方法轻松地做到这一点:-

df['date']=pandas.to_datetime(df['date'])