django-trackstats icon indicating copy to clipboard operation
django-trackstats copied to clipboard

Always use UTC when getting the current time

Open sloria opened this issue 7 years ago • 5 comments

There are a number of places in the code that use

datetime.today()

According to the docs, this returns the date in the local timezone.

This could lead to a bug where a user could get different results based on the location of the app server.

I believe the fix is to do this instead:

from django.utils import timezone

today = timezone.now().date()

Which will always return the date for UTC.

sloria avatar Apr 30 '18 19:04 sloria

in settings.py you have to change the timezone.

serajushsalekin avatar May 01 '18 05:05 serajushsalekin

@serajushsalekin No, timezone.now() always returns the time in UTC (as long as USE_TZ = True).

From the docs:

If USE_TZ is True, this will be an aware datetime representing the current time in UTC.


In [1]: settings.TIME_ZONE
Out[1]: u'America/Chicago'

In [2]: timezone.now()
Out[2]: datetime.datetime(2018, 5, 1, 15, 29, 46, 420714, tzinfo=<UTC>)

sloria avatar May 01 '18 15:05 sloria

its return UTC because it is default. #settings.py TIME_ZONE = 'America/Chicago'

USE_I18N = True

USE_L10N = True

USE_TZ = True

serajushsalekin avatar May 02 '18 06:05 serajushsalekin

@serajushsalekin Yes, timezone.now() returns a UTC datetime because USE_TZ = True. Consequently, timezone.now() will have deterministic output, i.e. it will not depend on the timezone of the server the app is running from.

sloria avatar May 02 '18 12:05 sloria

https://stackoverflow.com/questions/16037020/djangos-timezone-now-does-not-show-the-right-time

>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2019, 9, 19, 12, 30, 44, 798658, tzinfo=<UTC>)
>>> timezone.localtime(timezone.now())
datetime.datetime(2019, 9, 19, 14, 31, 2, 11144, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
>>> 

AcckiyGerman avatar Sep 19 '19 12:09 AcckiyGerman