How to convert Year and Day of Year to Date?

PythonDateJulian Date

Python Problem Overview


I have a year value and a day of year and would like to convert to a date (day/month/year).

Python Solutions


Solution 1 - Python

datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)

Solution 2 - Python

>>> import datetime
>>> datetime.datetime.strptime('2010 120', '%Y %j')
datetime.datetime(2010, 4, 30, 0, 0)
>>> _.strftime('%d/%m/%Y')
'30/04/2010'

Solution 3 - Python

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)

Solution 4 - Python

since it is pretty common these days, a pandas option, using pd.to_datetime with specified unit and origin:

import pandas as pd

day, year = 21, 2021

print(pd.to_datetime(day-1, unit='D', origin=str(year)))
# 2021-01-21 00:00:00

Solution 5 - Python

>>>import datetime
>>>year = int(input())
>>>month = int(input())
>>>day = int(input())
data = datetime.datetime(year,month,day)
daynew = data.toordinal()
yearstart = datetime.datetime(year,1,1)
day_yearstart = yearstart.toordinal()
print ((daynew-day_yearstart)+1)

Solution 6 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMinoView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonSilentGhostView Answer on Stackoverflow
Solution 3 - PythonsthView Answer on Stackoverflow
Solution 4 - PythonFObersteinerView Answer on Stackoverflow
Solution 5 - PythonEgor014View Answer on Stackoverflow
Solution 6 - PythonUse MeView Answer on Stackoverflow