如果我错了,请原谅,但是当数据为空或空时,将发生AFAIK ValueError: NaTType does not support strftime
。但我的数据不是。
假设我有这个数据帧。
df = pd.DataFrame({'personnel_number': ['123', '345', '567', '789', '000', '4444'],
'expiry_date': ['2020-12-07', '2099-12-04', '2019-08-30', '2022-03-19', '2020-09-06', '9999-12-31']})
我想用下面的代码把它转换成日期类型的格式。
for exp_date in df['expiry_date']:
date = pd.to_datetime(exp_date, errors='coerce').strftime('%Y-%m-%d')
print(date)
但不知何故,当循环到达最后一个数据( '9999-12-31‘日期数据)时,我总是得到这个错误。
ValueError: NaTType does not support strftime
我认为9999年听起来没有意义,但这是我拥有的数据,我不能改变它。那么,我能做什么呢?
发布于 2019-11-20 15:24:25
我认为这里没有必要使用循环,先对column使用pd.to_datetime
,然后使用Series.dt.strftime
df['expiry_date'] = pd.to_datetime(df['expiry_date'], errors='coerce').dt.strftime('%Y-%m-%d')
print(df)
personnel_number expiry_date
0 123 2020-12-07
1 345 2099-12-04
2 567 2019-08-30
3 789 2022-03-19
4 000 2020-09-06
5 4444 NaT
错误的原因是参数errors='coerce'
create missing values NaT
for 'wrong'
datetimes,因为这里超出了限制,timestamp limitations
In [92]: pd.Timestamp.min
Out[92]: Timestamp('1677-09-21 00:12:43.145225')
In [93]: pd.Timestamp.max
Out[93]: Timestamp('2262-04-11 23:47:16.854775807')
https://stackoverflow.com/questions/58948809
复制相似问题