Converting days since epoch to date

我的未来我决定 提交于 2019-12-10 09:25:00

问题


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.


回答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"


来源:https://stackoverflow.com/questions/39986041/converting-days-since-epoch-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!