【问题标题】:Incorrect results of converting between python datetime and timestamppython datetime和timestamp之间的转换结果不正确
【发布时间】:2015-08-20 01:45:14
【问题描述】:

以下代码的输出完全错误:

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 小时。 知道发生了什么吗?

【问题讨论】:

  • 我认为你错了。 10:00:0017:12:00之间的时间相差7.2小时。
  • @Cyphase 是的,是7.2小时,但是1380204000和1388355120的差应该是94天+8.2小时,而不是7.2小时
  • 也许是夏令时?
  • 是的,你是对的。谢谢!

标签: python datetime time timestamp


【解决方案1】:

您的问题是夏令时。时间戳之间的时间确实是 94 天 8.2 小时;但考虑到 DST,这意味着稍后时间的格式化时间将比您预期的时间晚一个小时。

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多