0

The output of following code is totally wrong:

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"

Here is the output:

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

The difference between two timestamps, 1380204000 and 1388355120, should be 94 days and 8.2 hours, while my results show a difference of 94 days and 7.2 hours. Any idea what happened?

5
  • I think you're mistaken. The time difference between 10:00:00 and 17:12:00 is 7.2 hours. Commented Aug 20, 2015 at 1:49
  • @Cyphase Yes, it is 7.2 hours, but the difference between 1380204000 and 1388355120 should be 94days + 8.2hours, not 7.2hours Commented Aug 20, 2015 at 1:51
  • Daylight Saving Time, perhaps? Commented Aug 20, 2015 at 1:54
  • @roymaztang DST - timeanddate.com/time/dst/2013.html Commented Aug 20, 2015 at 1:55
  • Yes, you are right. thanks! Commented Aug 20, 2015 at 1:59

1 Answer 1

2

Your issue is Daylight Saving Time. The time between the timestamps is indeed 94 days, 8.2 hours; but given DST, that means the formatted hour of the later time will be an hour behind where you expect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.