1

If I do:

>>> print datetime.fromtimestamp(time.mktime(time.gmtime())) - datetime.utcnow()

it prints:

0:59:59.618000

Why would the utcnow() give 4 hours offset from my local time and gmtime() 5 hours?

This prints -5 and:

print int(-time.timezone/60/60)

Isn't all this supposed to be UTC time?

Braiam
  • 1
  • 11
  • 47
  • 78
Guillaume Chevalier
  • 9,613
  • 8
  • 51
  • 79

3 Answers3

4

There is no 1 hour difference between time.gmtime() and datetime.utcnow() in Python. They both represent the same time in UTC timezone. time.gmtime() does not represent time in Europe/London timezone. There is no DST transition in UTC timezone. The utc offset in UTC timezone is always zero.

Your code is wrong. It is incorrect to use time.mktime() with time.gmtime() as an input unless your local timezone is UTC. Your local timezone is not utc as witnessed by time.timezone != 0.

Isn't all this supposed to be UTC time?

  • time.gmtime() returns UTC time as a time tuple
  • datetime.utcnow() returns UTC time as a naive datetime object
  • time.mktime() accepts local time and returns "seconds since the epoch"
  • datetime.fromtimestamp() accepts "seconds since the epoch" and returns the local time as a naive datetime object

To compare time.gmtime() and datetime.utcnow():

#!/usr/bin/env python
import time
from datetime import datetime

print(abs(datetime(*time.gmtime()[:6]) - datetime.utcnow()))
# -> 0:00:00.524724

The difference is not zero because a time tuple does not store microseconds otherwise both functions return the same time regardless of your local timezone.

If your intent is to find the utc offset of your local timezone then see Getting computer's utc offset in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
3

GMtime has a daylight savings time adjustment part of the year UTC doesn't.

stonemetal
  • 6,111
  • 23
  • 25
0

From the source:

UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.

Always measure and store time in UTC.

If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!

whereas GMtime has a daylight savings time adjustment

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331