how to strip year from dates in pandas datetime in python

You can extract the year from the pandas datetime object using the "dt" accessor and then subtracting it from the original datetime object. Here's an example:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({
    'date': ['2021-01-01', '2022-02-02', '2023-03-03']
})

# convert date column to pandas datetime
df['date'] = pd.to_datetime(df['date'])

# strip year from date column
df['yearless_date'] = df['date'] - pd.to_timedelta(df['date'].dt.year - 1970, unit='Y')

print(df)
337 chars
15 lines

This will output the following dataframe:

main.py
        date yearless_date
0 2021-01-01   1900-01-01
1 2022-02-02   1900-02-02
2 2023-03-03   1900-03-03
105 chars
5 lines

As you can see, the new "yearless_date" column contains the same dates as the original "date" column, but with the year stripped away.

related categories

gistlibby LogSnag