I have a year value and a day of year and would like to convert to a date (day/month/year).
58
votes
6 Answers
28
votes
7
votes
The toordinal() and fromordinal() functions of the date class could be used:
from datetime import date
date.fromordinal(date(year, 1, 1).toordinal() + days - 1)
2
votes
0
votes
0
votes
Using the mx.DateTime module to get the date is similar to what has been proposed above using datetime and timedelta. Namely:
import mx.DateTime as dt
date = dt.DateTime(yyyy,mm,dd) + dt.DateTimeDeltaFromDays(doy-1)
So, given that you know the year (say, 2020) and the doy (day of the year, say 234), then:
date = dt.DateTime(2020,1,1) + dt.DateTimeFromDays(233)
which returns
2020-08-21 00:00:00.00
The advantage of the mx.DateTime library is that has many useful features. As per description in its homepage:
- Parses date/time string values in an almost seamless way.
- Provides conversion routines to and from many different alternative date/time storage formats.
- Includes an easy-to-use C API which makes integration a breeze.
- Fast, memory efficient, accurate.
- Georgian and Julian calendar support.
- Vast range of valid dates (including B.C. dates).
- Stable, robust and portable (mxDateTime has been around for almost 15 years now).
- Fully interoperates with Python's time and datetime modules.