如何在数据帧中将python对象类型mm/dd/yyyy转换为ymd日期类型

2024-06-17 11:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

是的……我知道有一百万个答案,但任何答案都对我有用。我有一个类型为mm/dd/yyyy的列,如下所示(01/01/1948),我正在尝试将其转换为1948-01-01 00:00(日期类型)

我尝试了以下答案:

def conv_dates_series(df, col, old_date_format, new_date_format):

df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)

return(df)

然后:

old_date_format='%mm/%dd/%Y'
new_date_format='%Y-%m-%d'

conv_dates_series(nypd_complaint, nypd_complaint['CMPLNT_FR_DT'], old_date_format, 
new_date_format)

我得到的这个错误是:

KeyError: "None of [Index(['02/11/2015', '03/17/2012', '10/27/2016', '11/27/2014', '12/11/2013',\n '08/28/2013', '12/04/2013', '09/14/2013', '01/31/2013', '09/17/2016',\n ...\n '07/21/2018', '01/03/2018', '09/11/2018', '01/15/2018', '08/07/2018',\n '12/02/2018', '01/20/2018', '08/03/2018', '12/10/2018', '11/15/2018'],\n dtype='object', length=6982552)] are in the [columns]"

我还尝试:

nypd_complaint['CMPLNT_FR_DT'].strftime("%Y/%m/%d %H:%M")

以及:

nypd_complaint['CMPLNT_FR_DT'] = nypd_complaint['CMPLNT_FR_DT'].astype(np.datetime64)

以及:

nypd_complaint['CMPLNT_FR_DT'] = pd.to_datetime(nypd_complaint['CMPLNT_FR_DT'] 
).dt.strftime('%Y/%m/%d %H:%M')

以及:

我试图使用parse

我犯了一些错误,但几乎都是一样的,比如:“超出范围…”等等

多谢各位

PS:我们的目标是从2015年或2015年以下开始降低每个价值


Tags: 答案format类型dfnewdatedtcol