Home > Back-end >  Convert decimal Day-of-year dataframe to datetime with HH:MM
Convert decimal Day-of-year dataframe to datetime with HH:MM

Time:09-22

Is it possible to convert an entire column of decimal Day-Of-Year into datetime format YYYY-mm-dd HH:MM ? I tried counting the amount of seconds and minutes in a day, but decimal DOY is different from decimal hours.

Example:

DOY = 181.82015046296297 Converted to: Timestamp('2021-06-05 14:00:00')

Here the date would be a datetime object appearing only as 2021-06-05 14:00:00 in my dataframe. And the year I am interested in is 2021.

CodePudding user response:

Use Timedelta to create an offset from the first day of year

Input data:

>>> df
   DayOfYear
0        254
1        156
2        303
3         32
4        100
5          8
6        329
7         82
8        218
9        293
df['Date'] = pd.to_datetime('2021') \
               df['DayOfYear'].sub(1).apply(pd.Timedelta, unit='D')

Output result:

>>> df
   DayOfYear       Date
0        254 2021-09-11
1        156 2021-06-05
2        303 2021-10-30
3         32 2021-02-01
4        100 2021-04-10
5          8 2021-01-08
6        329 2021-11-25
7         82 2021-03-23
8        218 2021-08-06
9        293 2021-10-20
  • Related