简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM