python 日期时间和时间戳之间的转换结果不正确
Incorrect results of converting between python datetime and timestamp
下面代码的输出是完全错误的:
import time
from datetime import datetime
def sec_to_date(sec, format="%m/%d/%Y %H:%M:%S"):
tmp = datetime.fromtimestamp(sec)
fmtdate = tmp.strftime(format)
return fmtdate
def date_to_sec(fmtdate, format="%m/%d/%Y %H:%M:%S"):
t_tuple = time.strptime(fmtdate, format)
sec = time.mktime(t_tuple)
return sec
if __name__ == "__main__":
fmtdate = sec_to_date(1380204000)
print "1380204000 sec to date " + fmtdate
fmtdate = sec_to_date(1388355120)
print "1388355120 sec to date " + fmtdate
sec = date_to_sec("09/26/2013 10:00:00")
print "09/26/2013 10:00:00 to " + str(sec) + " sec"
sec = date_to_sec("12/29/2013 17:12:00")
print "12/29/2013 17:12:00 to " + str(sec) + " sec"
这是输出:
1380204000 sec to date 09/26/2013 10:00:00
1388355120 sec to date 12/29/2013 17:12:00
09/26/2013 10:00:00 to 1380204000.0 sec
12/29/2013 17:12:00 to 1388355120.0 sec
两个时间戳 1380204000 和 1388355120 之间的差异应该是 94 天 8.2 小时,而我的结果显示是 94 天 7.2 小时。
知道发生了什么吗?
您的问题是夏令时。时间戳之间的时间确实是94天,8.2小时;但是考虑到夏令时,这意味着稍后时间的格式化小时将比您预期的时间晚一个小时。
下面代码的输出是完全错误的:
import time
from datetime import datetime
def sec_to_date(sec, format="%m/%d/%Y %H:%M:%S"):
tmp = datetime.fromtimestamp(sec)
fmtdate = tmp.strftime(format)
return fmtdate
def date_to_sec(fmtdate, format="%m/%d/%Y %H:%M:%S"):
t_tuple = time.strptime(fmtdate, format)
sec = time.mktime(t_tuple)
return sec
if __name__ == "__main__":
fmtdate = sec_to_date(1380204000)
print "1380204000 sec to date " + fmtdate
fmtdate = sec_to_date(1388355120)
print "1388355120 sec to date " + fmtdate
sec = date_to_sec("09/26/2013 10:00:00")
print "09/26/2013 10:00:00 to " + str(sec) + " sec"
sec = date_to_sec("12/29/2013 17:12:00")
print "12/29/2013 17:12:00 to " + str(sec) + " sec"
这是输出:
1380204000 sec to date 09/26/2013 10:00:00
1388355120 sec to date 12/29/2013 17:12:00
09/26/2013 10:00:00 to 1380204000.0 sec
12/29/2013 17:12:00 to 1388355120.0 sec
两个时间戳 1380204000 和 1388355120 之间的差异应该是 94 天 8.2 小时,而我的结果显示是 94 天 7.2 小时。 知道发生了什么吗?
您的问题是夏令时。时间戳之间的时间确实是94天,8.2小时;但是考虑到夏令时,这意味着稍后时间的格式化小时将比您预期的时间晚一个小时。