pandas.to_datetime() 方法有一个 'infer_datetime_format' 参数,文档中说:
infer_datetime_format : boolean, default False
If True and no format is given, attempt to infer the format of the datetime strings,
and if it can be inferred, switch to a faster method of parsing them.
In some cases this can increase the parsing speed by ~5-10x.
所以将infer_datatime_format设置为true,保留format参数默认值即可,这对我来说有效。
以下是我的情况:
>>> hours_df.head()
Open High Close Low Volume
Date
2020-01-05T02:00:00.000Z 7457.9 7481.5 7431.3 7442.1 1147.57478328
2020-01-05T01:00:00.000Z 7374.8 7479 7374.8 7457.9 2709.45095966
2020-01-05T00:00:00.000Z 7354.9 7392.1 7354.2 7374.7 642.60575144
>>> hours_df.index
Index(['2020-01-05T02:00:00.000Z', '2020-01-05T01:00:00.000Z',
'2020-01-05T00:00:00.000Z'],
dtype='object', name='Date')
>>> hours_df.index = pd.to_datetime(hours_df.index, infer_datetime_format=True)
>>> hours_df.index
DatetimeIndex(['2020-01-05 02:00:00+00:00', '2020-01-05 01:00:00+00:00',
'2020-01-05 00:00:00+00:00'],
dtype='datetime64[ns, UTC]', name='Date', freq=None)
>>> hours_df.head()
Open High Close Low Volume
Date
2020-01-05 02:00:00+00:00 7457.9 7481.5 7431.3 7442.1 1147.57478328
2020-01-05 01:00:00+00:00 7374.8 7479 7374.8 7457.9 2709.45095966
2020-01-05 00:00:00+00:00 7354.9 7392.1 7354.2 7374.7 642.60575144
df.index = pd.to_datetime(df.index)
这个方法对于我来说可以处理你所发布的示例。 - Tom Ronpandas.to_datetime
时,它能在所有条目上正常工作,没有错误,并且结果正确。你得到了什么错误的结果? - elypd.to_datetime(df.index, errors='coerce')
。这可以处理两种格式,同时将完全不正确的日期强制转换为NaT
。在第一种情况下,由于有两个格式,其中一个格式将不匹配并引发错误,而使用errors ='ignore'
则会返回输入。 - ALollzDataframe
的head
。 - Pedro Lobito