Search code examples
pythondatetimemathformula

Calculate year and julian date from a value that is n days since start date


I have a time series dataset and I need to convert the date format. Currently the 'time' value represents the number of days since 01011961 (ddmmyyyy). I need to convert this to two values, one for the year and the other for the julian date.

Assuming the 'time' value in the dataset is x, I have tried the formula below(this is in python but the code is less important than the formula). However, the resulting dates are off because they are skewed by leap years:

year = [int(1961 + (x/365)) for x in time]
date = [int((x) - (((year[0]-1961)*365)+9))for x in time] #the +9 was to account for previous leap years but it's not quite right

Solution

  • Don't try to compute it yourself. You can do this with the datetime module:

    xxxxx:~/src$ python
    Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import datetime
    >>> epoch = datetime.date(1969,1,1)
    >>> d=epoch+datetime.timedelta(days=12345)
    >>> d
    datetime.date(2002, 10, 20)
    >>> d.timetuple().tm_yday
    293
    >>> d.timetuple().tm_year
    2002
    >>>