python mktime(.timetuple()) returns different results in mac and linux

时间:2016-07-11 19:29:54

标签: python

I noticed time.mktime(.timetuple()) returned different time on mac and linux(ubuntu). Why this?

date = ['2016-07-01', '2016-07-05']

xdata = [datetime.datetime.strptime(str(s), "%Y-%m-%d") for s in date]
xdata = [time.mktime(s.timetuple()) * 1000 for s in xdata]
print xdata

# ----mac--
>> [1467356400000.0, 1467702000000.0]

#-----linux---
>> [1467345600000.0, 1467691200000.0]

How to return in UTC?

1 个答案:

答案 0 :(得分:0)

I marked to close this as a duplicate, but it's really not if you're viewing your original inputs as being in UTC to begin with. If you are (it's not wholly clear), then just replace your time.mktime with calendar.timegm.

>>> d = datetime.datetime(2016, 9, 1)
>>> calendar.timegm(d.timetuple())
1472688000

Or you can do it all yourself:

>>> EPOCH = datetime.datetime(1970, 1, 1)
>>> def dt2utcstamp(d):
...     return (d - EPOCH).total_seconds()

and then:

>>> dt2utcstamp(d)
1472688000.0

I generally do the latter, because I find it next to impossible to remember what all the goofy time-and-date functions do ;-) But the timedelta.total_seconds() method doesn't exist before Python 3.2.

Or if you do view the inputs as being in local time, then the other answers apply:

How do I convert local time to UTC in Python?

NOTE

When you ask "How to return in UTC?", you have to realize that your original code already did that: timestamps are always viewed as being seconds from the epoch in UTC. Indeed, that's why you got different results on platforms set to different time zones to begin with: '2016-07-01'(with implied time 00:00:00) is a different real-world instant depending on which time zone it's viewed as being in.

The s.timetuple() part doesn't care about that, but it's a primary purpose of the time.mktime() part to convert the local time to a UTC timestamp.