user3595632
user3595632

Reputation: 5730

Django: Can not understand TIME_ZONE configuration

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

Upvotes: 0

Views: 649

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

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

Upvotes: 2

Related Questions