【问题标题】:django timezone is taken as UTC even though I have set it to 'Asia/Kolkata'django 时区被视为 UTC,即使我已将其设置为“亚洲/加尔各答”
【发布时间】:2018-04-29 11:41:01
【问题描述】:

这是我在 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 时间。我错过了什么

【问题讨论】:

    标签: django timezone


    【解决方案1】:

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

    Django 仅在templates 中将时间转换为指定的时区(Asia/Kolkata)。所以,如果你想在代码(views/models)的某个地方使用你的本地时间(Asia/Kolkata),你必须使用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()

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2020-10-28
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多