pythonpython-3.xdatedate-conversionjulian-date

Converting 6-digit Julian date to std date


I have 6-digit Julian dates from DB table, and I am trying to convert them to std date. I get error as the format is not correct. fmt = '%y%m%j'

This is the function I have written:

import datetime
def jdtodatestd (jdate):
    fmt = '%y%m%j'
    datestd = datetime.datetime.strptime(jdate, fmt).date()
    return(datestd)
x = jdtodatestd('122105')
print(x)

In above Julian date "122105":
1 is Century code
22 is Year
105 is 105th day of the year.

I am getting 2012-04-14 as result, but the expected result is 2022-04-15.


Solution

  • Insert jdate = str(19 + int(jdate[0])) + jdate[1:] into your Python function and change format to %Y%j

    import datetime
    def jdtodatestd (jdate):
        jdate = str(19 + int(jdate[0])) + jdate[1:]
        fmt = '%Y%j'
        datestd = datetime.datetime.strptime(jdate, fmt).date()
        return(datestd)
    x = jdtodatestd('122105')
    
    print(x)
    # 2022-04-15