Python / Pandas: Convert 'Day of Year' Integer into Full Date

Viewed 424

I know with a Datetime object, I can extract the numeric day of year (e.g. January 1st = 1, December 31st = 365) with .dayofyear like this:

some_datetime.dayofyear

Is there a way I can reverse this and take an integer for the dayofyear and convert it back to a full date?

I searched through datetime and tried a few things, but nothing seemed to work.

2 Answers

You can do:

df['date'] = df['days'].apply(lambda x: dt + pd.Timedelta(f'{x}D'))
print(df)

   days       date
0    32 2020-02-02
1   150 2020-05-30
2   200 2020-07-19

Sample Data

# set some start date 
dt = pd.to_datetime('2020-01-01')
df = pd.DataFrame({'days': [32, 150, 200]})

An interesting alternative is to use the origin parameter of pandas’ to_datetime() :

days = [32, 150, 200]
pd.to_datetime([d-1 for d in days], unit='D', origin=pd.Timestamp('01-01-2020'))

Be sure to subtract one day since the first day is already accounted for in the initialization.

Credits go there.

Related