dataframe to_datetime 没有正确读取日期

dataframe to_datetime not reading dates correctly

excel 文件的一部分如下。

Action Date1               Action Date2
15.06.2018 - 06:06:30   17.06.2018 - 15:52:35
09.07.2018 - 10:12:13   09.07.2018 - 11:39:42
09.08.2018 - 15:21:45   
10.07.2018 - 10:00:13   00.00.0000 - 00:00:00

......

我想提取最新的动作日期,我有以下代码

dates = df.fillna(axis=1, method='ffill')
df['Latest date'] = dates[dates.columns[-1]]

但是这个代码 returns 正确的日期如下。

2018-06-17 15:52:35
2018-09-07 11:39:42
2018-09-08 15:21:45
2018-10-07 10:00:13

.....

我试过了

df['Latest date']=pd.to_datetime(df['Latest date'],format="%d%m%Y")

但它仍然给我同样的结果。

使用参数format,勾选http://strftime.org/:

df['Latest date']=pd.to_datetime(df['Latest date'],format="%d.%m.%Y - %H:%M:%S")

或参数dayfirst=True:

df['Latest date']=pd.to_datetime(df['Latest date'], dayfirst=True)

print (df)
          Latest date
0 2018-06-15 06:06:30
1 2018-07-16 08:53:49
2 2018-07-09 10:12:13
3 2018-08-09 15:21:45

编辑:添加参数 errors='coerce' 用于将不可解析的值转换为 NaT:

df = df.apply(lambda x: pd.to_datetime(x,format="%d.%m.%Y - %H:%M:%S", errors='coerce'))
dates = df.ffill(axis=1)
df['Latest date'] = dates.iloc[:, -1]
print (df)
        Action Date1        Action Date2         Latest date
0 2018-06-15 06:06:30 2018-06-17 15:52:35 2018-06-17 15:52:35
1 2018-07-09 10:12:13 2018-07-09 11:39:42 2018-07-09 11:39:42
2 2018-08-09 15:21:45                 NaT 2018-08-09 15:21:45
3 2018-07-10 10:00:13                 NaT 2018-07-10 10:00:13