Get local timezone in django

后端 未结 9 594
轻奢々
轻奢々 2020-12-04 17:47

I have a mysql DATETIME value that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:

相关标签:
9条回答
  • 2020-12-04 18:40

    I have came to the same problem. In my settings, I have set the TIME_ZONE, but the time in MySql still UTC time.

    # settings.py
    TIME_ZONE = 'Asia/Shanghai'
    

    Then I found,in settings.py, USE_TZ has be set to False

    USE_TZ = False

    As pointed out by @MagicLAMP, it only works for single time zone site, please check time-zones if your site is international or if daylight savings happen where your site is used.

    0 讨论(0)
  • 2020-12-04 18:46

    1: Define the timezone in your view

    from django.utils import timezone
    
    variable = timezone.now()
    

    2: Then use it in your template

    {% load l10n %}
    
    Teresina, {{variable |localize}}.
    
    0 讨论(0)
  • 2020-12-04 18:47

    localtime is a template filter, this may be helpful.

    https://github.com/django/django/blob/1.8.4/django/utils/timezone.py#L298

    Code sample:

    from django.utils.timezone import localtime 
    
    desired_datetime = localtime(stored_datetime)
    
    0 讨论(0)
提交回复
热议问题