Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always use UTC when getting the current time #11

Open
sloria opened this issue Apr 30, 2018 · 5 comments
Open

Always use UTC when getting the current time #11

sloria opened this issue Apr 30, 2018 · 5 comments

Comments

@sloria
Copy link
Contributor

sloria commented Apr 30, 2018

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.

@serajushsalekin
Copy link

in settings.py you have to change the timezone.

@sloria
Copy link
Contributor Author

sloria commented May 1, 2018

@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>)

@serajushsalekin
Copy link

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

USE_I18N = True

USE_L10N = True

USE_TZ = True

@sloria
Copy link
Contributor Author

sloria commented May 2, 2018

@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.

@AcckiyGerman
Copy link

AcckiyGerman commented Sep 19, 2019

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>)
>>> 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants