我需要帮助:pandas数据集有一个日期列。其中一列的日期格式为"September 25, 2021"。我无法将其转换为"yyyy-mm-dd"格式(2021-09-25)。这是必要的,以便在将来将这些数据导入mysql(我通过debever工作)。这可能是一个愚蠢的问题,但我是一个新手
尝试使用to_datetime函数,这种方式(IndexError: list index out of range):
date = {'January': '01', 'February': '02', 'March': '03', 'April': '04', 'May': '05', 'June': '06',
'July': '07', 'August': '08', 'September': '09', 'October': '10', 'November': '11', 'December': '12'}
new_date = []
for d in df['date_added']:
month = d.split(' ')[0]
day = d.split(' ')[1]
year = d.split(', ')[2]
res = year.split('-') + date[month].split('-') + day
new_date.append(res)
import pandas as pd
df = pd.DataFrame({'date_added': ['September 25, 2010', 'April 1, 2023']})
r = pd.to_datetime(df['date_added'], format='%B %d, %Y')
print(r)
结果
0 2010-09-25
1 2023-04-01
Name: date_added, dtype: datetime64[ns]
我认为你可以使用strftime。下面是一个例子:
date_string = "September 25, 2021"
date = pd.to_datetime(date_string)
formatted_date = date.strftime('%Y-%m-%d')
print(formatted_date) #2021-09-25
import pandas as pd
df = pd.DataFrame({'date_added': ['September 25, 2010', 'April 1, 2023']})
print(df)
print()
# If you need actually need datetime object
df.date_added = pd.to_datetime(df.date_added) # dtype = datetime64[ns]
print(df)
print()
# reset dataframe
df = pd.DataFrame({'date_added': ['September 25, 2010', 'April 1, 2023']})
# If you need a formatted string
df.date_added = pd.to_datetime(df.date_added).dt.strftime('%Y-%m-%d') # dtype = object
print(df)
输出:
date_added
0 September 25, 2010
1 April 1, 2023
date_added
0 2010-09-25
1 2023-04-01
date_added
0 2010-09-25
1 2023-04-01