You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame的‘Date of birth’列格式化为仅日期格式?

Fixing Date Formatting & Calculating Age in Pandas

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' in pd.to_datetime() is designed for dates like 30Apr1957, but your raw data uses the standard ISO format YYYY-MM-DD HH:MM:SS—so specifying that format caused a mismatch.
  • The second line converts dates to a MM/DD/YYYY string, which isn't the YYYY-MM-DD format 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:

  1. 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.

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:15:26