Nit*_*Das 3 python string-to-datetime pandas
我有一个 python pandas 数据框,它有一个如下所示的日期列:
'Birth Date'
0 22/04/73
1 22/03/53
2 22/04/73
3 14/08/77
4 08/05/50
Run Code Online (Sandbox Code Playgroud)
我想将此对象数据类型转换为日期格式,如下所示:04/06/1953...
我尝试转换为 datetime 数据类型,如下所示:
df['Birth Date']=pandas.to_datetime(df['Birth Date'],format='%d/%m/%y')
Run Code Online (Sandbox Code Playgroud)
但输出是这样的:
0 1973-04-22
1 2053-03-22
2 1973-04-22
3 1977-08-14
4 2050-05-08
Run Code Online (Sandbox Code Playgroud)
如何将 1953、1950 等作为年份而不是 2053、2050?
您需要通过掩码手动更改年份,例如所有年份2017减去100年份:
df['Birth Date']= pd.to_datetime(df['Birth Date'],format='%d/%m/%y')
df['Birth Date'] = df['Birth Date'].mask(df['Birth Date'].dt.year > 2017,
df['Birth Date'] - pd.offsets.DateOffset(years=100))
print (df)
Birth Date
0 1973-04-22
1 1953-03-22
2 1973-04-22
3 1977-08-14
4 1950-05-08
Run Code Online (Sandbox Code Playgroud)