在python datetime和timestamp之间转换的结果不正确

时间:2015-08-20 01:45:14

标签: python datetime time 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小时之间的差异。 知道发生了什么吗?

1 个答案:

答案 0 :(得分:2)

您的问题是夏令时。时间戳之间的时间确实是94天,8.2小时;但是在DST的情况下,这意味着较晚时间的格式化小时将落后于您期望的一小时。