【Python】处理时间数据格式出现time data does not match format valueError

今天在处理时间数据格式的时候出现了下面这种错误:

ValueError: time data '19970004' does not match format '%Y%m%d' (match)

转变时间数据格式的代码如下:

data['used_time'] = (pd.to_datetime(data['creatDate'], format='%Y%m%d') - 
                      pd.to_datetime(data['regDate'], format='%Y%m%d')).dt.days

根据错误提示,出现错误的原因是数据中有时间出错的格式。

通过修改在to_datetime()函数里面有errors参数,可以解决这个问题。

data['used_time'] = (pd.to_datetime(data['creatDate'], format='%Y%m%d', errors='coerce') - 
                      pd.to_datetime(data['regDate'], format='%Y%m%d', errors='coerce')).dt.days

errors参数共有三种赋值,默认的值为‘raise’,出现不符合规范的解析时就会报错。可以将errors参数赋值为‘coerce’,在解析的过程中将出错的时间格式设置为NaT。如果不想处理错误的时间格式,可以将errors赋值为‘ignore’,这样就还是原来的格式。

errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

  • If ‘raise’, then invalid parsing will raise an exception.

  • If ‘coerce’, then invalid parsing will be set as NaT.

  • If ‘ignore’, then invalid parsing will return the input.

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值