在R语言中将数据框字符型日期转换为‘YYYY-MM-DD’格式
Solution for Converting World Cup Match Dates to YYYY-MM-DD Format
Hey there! Let's get that date column converted properly for your 2018 World Cup dataframe. The key here is using pandas' to_datetime method to parse the abbreviated date strings, then format them to your desired YYYY-MM-DD style.
Step-by-Step Implementation
First, let's replicate your original dataframe and then apply the conversion:
import pandas as pd # Create your original dataframe data = { 'date': ['Thu Jun 14', 'Fri Jun 15', 'Tue Jun 19', 'Wed Jun 20'], 'match_name': ['Russia v Saudi Arabia', 'Egypt v Uruguay', 'Russia v Egypt', 'Uruguay v Saudi Arabia'], 'price': ['€453.92', '€90.00', '€297.45', '€95.00'] } df = pd.DataFrame(data) # Convert the date column # Parse the string to datetime (add 2018 since it's the 2018 World Cup) df['date'] = pd.to_datetime(df['date'], format='%a %b %d', year=2018) # Optional: Format as string in YYYY-MM-DD style (skip if you want datetime type) df['date'] = df['date'].dt.strftime('%Y-%m-%d') # Check the result print(df)
What This Does
pd.to_datetime(df['date'], format='%a %b %d', year=2018): Parses the date strings using the format specifier:%a: Abbreviated weekday name (e.g., Thu)%b: Abbreviated month name (e.g., Jun)%d: Day of the month (two digits)- We manually add
year=2018since the original data doesn't include the year (and we know this is the 2018 World Cup).
.dt.strftime('%Y-%m-%d'): Converts the datetime object to a string in your desiredYYYY-MM-DDformat. If you want to keep the column as a datetime type (better for future date operations), you can skip this line.
Quick Correction Note
Your expected result shows dates like 2018-05-14, but Jun stands for June, not May. The code above will correctly output dates like 2018-06-14, which aligns with the actual 2018 World Cup schedule.
内容的提问来源于stack exchange,提问作者Hüseyin
相关产品推荐
相关产品推荐

