James George Dunn
James George Dunn

Reputation: 523

Adding a year to the end of a date using Python

I've got a DataFrame that has dates such as Nov-28 and Jan-12. Now the date such as Nov-28 is for this year (2020) and the other dates are for next (2021).

I'm wondering if there's a way to determine if a date is less than today to add next years year to it?

Upvotes: 1

Views: 271

Answers (1)

jezrael
jezrael

Reputation: 862481

Idea is first add actual year to to_datetime and then test if greater like now add one year by offsets.DateOffset:

df = pd.DataFrame({'date':['Nov-28','Jan-12']})

now = pd.Timestamp('now')

df['date'] = pd.to_datetime(str(now.year) + df['date'], format='%Y%b-%d')

df.loc[df['date'] > now, 'date'] += pd.offsets.DateOffset(years=1)
print (df)
        date
0 2021-11-28
1 2020-01-12

Upvotes: 1

Related Questions