简体   繁体   English

转换自纪元至今的天数

[英]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?如何将表示自纪元(1970)以来的天数的序列日期数字转换为相应的日期字符串? 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" .例如, 15951对应于"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.) + 1因为生成这些日期数字的任何内容都遵循 1970 年 1 月 1 日 = 1 的约定。)

TL;DR: Looking for something to do the following: TL;DR:正在寻找可以执行以下操作的方法:

>>> 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.这与Python不同:Converting Epoch time into the datetime因为我从 1970 年以来的天开始。我不确定你是否可以因为闰秒等原因乘以 86,400。

Use the datetime package as follows:使用datetime包如下:

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"

And for a Pandas Dataframe:对于 Pandas 数据框:

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 . ...假设“日期”列包含像18687这样的值,它是从 Unix Epoch of 1970-01-012021-03-012021-03-01

Also handles seconds and milliseconds since Unix Epoch, use unit="s" and unit="ms" respectively.还处理自 Unix Epoch 以来的秒和毫秒,分别使用unit="s"unit="ms"

Also see my other answer with the exact reverse .另请参阅我的其他完全相反的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM