Search code examples
timeleap-year

Is there library to convert number of days in a specific year to month and date?


I have an information which contains specific year and number of days. For example, 2000137 means May 16, 2000 because May 16 is the 137th day of year 2000. I need those numbers like 2000137 in the format 2000-05-16. I can do such conversion by considering how many days are in each month and how many days are in each year but I need to take the leap years into consideration and it seems too tedious to implement such code. I wonder if there is simple function in Excel or Python to do such conversion.


Solution

  • You can achieve the above using Python's fromordinal and toordinal functions in the datetime library.

    Try the following:

    from datetime import date
    ip=2000137
    year=ip//1000
    days=ip%1000
    #days until that year
    days_till_year=date(year,1,1).toordinal()
    days_till_input=days_till_year+days-1
    print(date.fromordinal(days_till_input))
    

    The output would be:

    2000-05-16