django timezone被视为UTC,即使我已将其设置为'Asia / Kolkata'

时间:2018-04-29 11:41:02

标签: django timezone

这是我在settings.py中的时区设置

TIME_ZONE =  'Asia/Kolkata'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = False

现在当我使用timezone.now()时,我总是得到UTC时间。我错过了什么

1 个答案:

答案 0 :(得分:3)

首先,您必须设置USE_TZ = True才能使用该功能。

Django仅在Asia/Kolkata中将时间转换为指定的时区(templates)。因此,如果您想在代码(Asia/Kolkata)的某处使用当地时间(views/models),则必须使用localtime()方法。按照代码来实现它:

<强> settings.py

TIME_ZONE = 'Asia/Kolkata'
USE_TZ = True

和,

from django.utils import timezone

my_local_time = timezone.localtime(timezone.now())

django shell中的示例

In [1]: from django.utils import timezone

In [2]: timezone.now()
Out[2]: datetime.datetime(2018, 4, 29, 14, 5, 30, 112218, tzinfo=<UTC>)

In [3]: timezone.localtime(timezone.now())
Out[3]: datetime.datetime(2018, 4, 29, 19, 35, 46, 649587, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

参考文献:

  1. SO post
  2. localtime()