Skip to content Skip to sidebar Skip to footer

Converting Days Since Epoch To Date

How can one convert a serial date number, representing the number of days since epoch (1970), to the corresponding date string? I have seen multiple posts showing how to go from st

Solution 1:

Use the datetime package as follows:

import datetime
def serial_date_to_string(srl_no):
    new_date = datetime.datetime(1970,1,1,0,0) + datetime.timedelta(srl_no - 1)
    return new_date.strftime("%Y-%m-%d")

This is a function which returns the string as required.

So:

serial_date_to_string(15951)

Returns

>>"2013-09-02"

Solution 2:

And for a Pandas Dataframe:

df["date"] = pd.to_datetime(df["date"], unit="d")

... assuming that the "date" column contains values like 18687 which is days from Unix Epoch of 1970-01-01 to 2021-03-01.

Also handles seconds and milliseconds since Unix Epoch, use unit="s" and unit="ms" respectively.

Also see my other answer with the exact reverse.

Post a Comment for "Converting Days Since Epoch To Date"