2

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?

DougKruger
  • 4,424
  • 14
  • 41
  • 62
  • What does `time.mktime(time.gmtime(0))` return on each platform? If that differs too, the platforms are set to different time zones. `mktime()` views its input as being in "local time". The results you're seeing differ by 3 hours. – Tim Peters Jul 11 '16 at 19:55
  • yes, its very possible the timezones are different. How to convert from local to UTC? – DougKruger Jul 11 '16 at 19:58
  • @TimPeters results defers on both platforms. Linux returns `18000.0 ` while Mac returns `28800.0` – DougKruger Jul 11 '16 at 20:01
  • Given that you really want to convert to a UTC timestamp, I marked to close this as a duplicate question - see the link I supplied. – Tim Peters Jul 11 '16 at 20:02

1 Answers1

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.

Community
  • 1
  • 1
Tim Peters
  • 67,464
  • 13
  • 126
  • 132