I have the day of the year (e.g. 295). I want to convert that to it's equivalent, October 22. I have this for multiple years so each time the routine should update the year once it reaches 365 or 366. Is there any built in function for this?
Asked
Active
Viewed 55 times
1
-
2Does this answer your question? [Python Question: Year and Day of Year to date?](https://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date) – blacksite Apr 10 '20 at 14:28
-
@blacksite It does for the first part. Any idea how to update the years? – Shreya Apr 10 '20 at 14:34
-
1It should be automatic `pd.to_datetime('2000-01-01') + df.to_timedelta(df['day'], unit='D')`, remember to replace `2000-01-01` with your start year. – Quang Hoang Apr 10 '20 at 14:36
-
@QuangHoang Thanks for your help but the year is still not updating. – Shreya Apr 10 '20 at 14:43
2 Answers
1
I'm not sure why you mentioned in the comment that the year is not updating:
s = pd.Series([1,20,56,290,356,3,5,7,100])
start_year = 2000
# calculate the years
years = s.diff().lt(0).cumsum()+start_year
# final output
pd.to_datetime(years, format='%Y') + pd.to_timedelta(s-1, unit='D')
Output:
0 2000-01-01
1 2000-01-20
2 2000-02-25
3 2000-10-16
4 2000-12-21
5 2001-01-03
6 2001-01-05
7 2001-01-07
8 2001-04-10
dtype: datetime64[ns]

Quang Hoang
- 146,074
- 10
- 56
- 74
0
I think that's what you are looking for:
import datetime
x = datetime.datetime.strptime('2019 110', '%Y %j')
x.strftime('%B %d')
'April 30'

dp6000
- 473
- 5
- 15
-
Thank you, but this is for a single year. I have a data-frame column with days from multiple years placed sequentially. So I am looking for something to upgrade the year once it reaches 365/366 – Shreya Apr 10 '20 at 14:46
-
You can't apply it to all the column ? You can use the lambda function for that – dp6000 Apr 10 '20 at 14:56