如何将DataFrame的‘Date of birth’列格式化为仅日期格式?
Hey there! Let's sort out your date formatting issue and set you up for calculating ages smoothly.
First, let's break down why your original code didn't work:
- The
format='%d%b%Y'inpd.to_datetime()is designed for dates like30Apr1957, but your raw data uses the standard ISO formatYYYY-MM-DD HH:MM:SS—so specifying that format caused a mismatch. - The second line converts dates to a
MM/DD/YYYYstring, which isn't theYYYY-MM-DDformat you want, and converting to strings can make age calculations harder later.
Step 1: Convert to Datetime Type (Correctly)
First, ensure your column is properly parsed as datetime. Since your data is already in a standard format, you don't need the format parameter at all:
import pandas as pd # Parse the column to datetime (automatically handles the ISO format) df["Date of birth"] = pd.to_datetime(df["Date of birth"])
Step 2: Get Pure Date Format (Two Options)
Choose based on your needs:
Keep as Datetime Type (best for age calculations)
This removes the time component but keeps the column as a datetime dtype, which is ideal for date arithmetic:# Remove time component (sets time to 00:00:00 but keeps datetime type) df["Date of birth"] = df["Date of birth"].dt.normalize() # Alternative: use floor to day # df["Date of birth"] = df["Date of birth"].dt.floor("D")When you print the DataFrame, it will display just the date (e.g.,
1957-04-30) instead of the full timestamp.Convert to String (YYYY-MM-DD)
If you specifically need a string column in that exact format:df["Date of birth"] = df["Date of birth"].dt.strftime("%Y-%m-%d")
Step 3: Calculate Age from Birth Date
Now that your dates are properly formatted, here's how to calculate age accurately (accounting for whether the person has had their birthday this year):
from datetime import datetime def calculate_age(birth_date): today = datetime.today() age = today.year - birth_date.year # Subtract 1 if birthday hasn't occurred yet this year if (today.month, today.day) < (birth_date.month, birth_date.day): age -= 1 return age # Apply the function (works if "Date of birth" is datetime type) df["Age"] = df["Date of birth"].apply(calculate_age)
That should get you exactly the formatted dates you want, plus a reliable age calculation!
内容的提问来源于stack exchange,提问作者Stacey

