转换自时代以来的天数 [英] Converting days since epoch to date
问题描述
如何将代表时代(1970年)以来的天数的序列号转换为相应的日期字符串?我看过多个帖子,它们显示了如何从字符串到日期数字,但是我却找不到关于如何执行相反操作的任何帖子。
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.
例如, 15951
对应于 2013-09-02
。
>>> import datetime
>>> (datetime.datetime(2013, 9, 2) - datetime.datetime(1970,1,1)).days + 1
15951
( +1
,因为生成这些日期数字的原因均遵循1970年1月1日= 1的约定。)
(The + 1
because whatever generated these date numbers followed the convention that Jan 1, 1970 = 1.)
TL; DR:正在寻找以下内容:
TL;DR: Looking for something to do the following:
>>> serial_date_to_string(15951) # arg is number of days since 1970
"2013-09-02"
这不同于 Python:将纪元时间转换为日期时间因为我是从1970年开始的几天。由于sure秒等原因,我不确定是否可以乘以86,400。
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.
推荐答案
按以下方式使用 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.
所以:
serial_date_to_string(15951)
返回
>> "2013-09-02"
这篇关于转换自时代以来的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!