Search code examples
pythonpandasdataframejulian-date

Convert Julian Date with Time to full datetime in pandas dataframe


I have a field in a pandas data frame where I calculated the Julian date using to_julian_date() from a datetime64[ns] field and now have values like jul1 in the example below:

df = pd.DataFrame({'dates':['2017-01-01 03:15:00','2017-01-01 03:15:00']})
df['dates'] = pd.to_datetime(df['dates'])

df['jul1'] = pd.DatetimeIndex(df['dates']).to_julian_date()
#if need remove times
df['jul2'] = pd.DatetimeIndex(df['dates']).floor('d').to_julian_date()
print (df)
                dates          jul1       jul2
0 2017-01-01 03:15:00  2.457755e+06  2457754.5

My question is: how can I convert a Julian date with time like this back into a full calendar date with time that includes the full temporal resolution possible? So if I’ve fed in a datetime down to seconds to generate the Julian equivalent, how do I reverse that Julian date back out to the full datetime?


Solution

  • I stumbled across this question when trying to do the same thing myself. Turns out the solution is quite simple, but not obvious to find in the documentation. Using your example from above, I've just added the final line.

    df = pd.DataFrame({'dates':['2017-01-01 03:15:00','2017-01-01 03:15:00']})
    df['dates'] = pd.to_datetime(df['dates'])
    
    df['jul1'] = pd.DatetimeIndex(df['dates']).to_julian_date()
    #if need remove times
    df['jul2'] = pd.DatetimeIndex(df['dates']).floor('d').to_julian_date()
    
    df['dates_recovered'] = pd.to_datetime(df['jul1'], unit='D', origin='julian')
    

    It think it would be helpful if there was a from_julian_date method to accompany the to_julian_date method.