Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 string to date number, but I haven't been able to find any posts on how to do the reverse.

For example, 15951 corresponds to "2013-09-02".

>>> import datetime
>>> (datetime.datetime(2013, 9, 2) - datetime.datetime(1970,1,1)).days + 1
15951

(The + 1 because whatever generated these date numbers followed the convention that Jan 1, 1970 = 1.)

TL;DR: Looking for something to do the following:

>>> serial_date_to_string(15951)  # arg is number of days since 1970
"2013-09-02"

This is different from Python: Converting Epoch time into the datetime because I am starting with days since 1970. I not sure if you can just multiply by 86,400 due to leap seconds, etc.

like image 972
pault Avatar asked Oct 11 '16 20:10

pault


People also ask

How do I convert epoch time to manual date?

use strict; use warnings; use Time::Piece; my $datestring = '07-06-2019 21:13:00'; my $time = localtime->strptime($datestring, '%d-%m-%Y %H:%M:%S'); my $epoch = $time->epoch; ... my $time = localtime($epoch); my $datestring = $time->strftime('%d-%m-%Y %H:%M:%S');

How many days has it been since the epoch?

For example, today, Fri 23rd April 2021 - timestamp at 00:00:00 UTC was 1619136000. As expected, this is a multiple of 86400, and 1619136000 / 86400 = 18740. There have been 18740 days since the unix epoch.

What is epoch date format?

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).


2 Answers

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"
like image 130
AER Avatar answered Sep 18 '22 02:09

AER


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.

like image 31
Contango Avatar answered Sep 20 '22 02:09

Contango