0

I have tested some timezone configuration to better understand about how django timezone works.

But still cannot understand how it works.

Have some questions and need your helps

Q1.

from django.utils import timezone
from datetime import datetime

1. TIME_ZONE='UTC', USE_TZ=True
    - datetime.now() => 2018-02-13 23:26:01.576493      // naive..
2. TIME_ZONE='Asia/Seoul', USE_TZ=True
    - datetime.now() => 2018-02-13 23:26:01.576493    // tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>

=> Why in 'UTC' case return naive datetime object...? As like in 2, I think it should return the tzinfo=<UTC> object...

Q2.

from django.utils import timezone
from datetime import datetime

1. TIME_ZONE='Asia/Seoul', USE_TZ=True
    - timezone.now() => 2018-02-13 23:25:32.768780    // tzinfo=<UTC> object

2. TIME_ZONE = 'Asia/Seoul', USE_TZ = False
    - timezone.now() => 2018-02-14 08:24:04.810045    // naive

=> why does timezone.now() returns tzinfo=<UTC> object in first case, even though I set the TIME_ZONE as 'Asia/Seoul'?

Q3.

1. TIME_ZONE = 'Asia/Seoul', USE_TZ = False
    - timezone.localtime() => ValueError: localtime() cannot be applied to a naive datetime

Why does it occur error even though I set a TIME_ZONE?

Additionally, cannot understand what exactly USE_TZ is (its role..etc) even after reading django official docs. I think that official documentation is like, easy to read only for the one who already knows what those are.. T_T

user3595632
  • 5,380
  • 10
  • 55
  • 111

1 Answers1

2

Q1.

datetime.now() is a Python utility, it has nothing to do with Django and will not be affected by any Django settings. In fact, your second result is incorrect, tzinfo will be None in both cases.

Q2.

From the documentation: "If USE_TZ is True, this will be an aware datetime representing the current time in UTC". TIME_ZONE is not relevant here.

Q3.

As above, if USE_TZ is False the datetime is naive. And the documentation says: "[localtime] doesn’t work on naive datetimes".

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • Thanks for correction and reply. One question more. If I use `PostgreSQL`, which support database timezone, shouldn't I set `TIME_ZONE` value like [this page](https://docs.djangoproject.com/en/2.0/ref/settings/#time-zone) said? – user3595632 Feb 14 '18 at 01:50
  • @user3595632: That page says that it's an error to set the `DATABASES` `TIME_ZONE` if you're using PostgreSQL, since you don't need Django to convert timezones on the fly when the database already supports them. As mentioned in the [database documentation](https://docs.djangoproject.com/en/dev/ref/databases/#optimizing-postgresql-s-configuration) Django will make sure it's PostgreSQL connections are using UTC. – Kevin Christopher Henry Feb 14 '18 at 02:46