将不正确的浮点数转换为日期

Converting improper float to date

我的数据框有这样的日期

dates
9112015.0
20032015.0
16042014.0

我试过了

pd.to_datetime(fraud_df['DATEOPENEDDISBURSED'], format='%d%m%Y',dayfirst=True) 

但它给我 ValueError: day is out of range for month

试试这个:

pd.to_datetime(fraud_df['DATEOPENEDDISBURSED'], format='%-d%m%Y',dayfirst=True) 

来自 Python strftime 备忘单 https://strftime.org/:

%-d 8 Day of the month as a decimal number. (Platform specific)

你必须

  • 填充 NaN
  • 转换为字符串
  • 并用零填充 z 以持续获得 zero-prefixed 天

EX:

import pandas as pd
import numpy as np

dates = pd.Series([9112015.0,20032015.0,16042014.0,np.nan])

# to get zero-prefixed days: to integer, then to string and zfill with zeros
dates = dates.fillna(-1).astype('int').astype('str').str.zfill(8)

# to datetime and coerce errors, giving NaT for the NaNs in the initial Series
pd.to_datetime(dates, format="%d%m%Y", errors='coerce')
0   2015-11-09
1   2015-03-20
2   2014-04-16
3          NaT
dtype: datetime64[ns]