[英]How to get the current user time zone? Django
我試圖讓我的 Django 應用程序與當前用戶時區一起工作,但我沒有得到任何結果......
在我的 settings.py 文件中,我設置了: TIME_ZONE = 'UTC'
在我的views.py
中我設置在代碼的頂部:
activate(settings.TIME_ZONE)
但這不起作用,在創建帖子時,正在獲取我的最后一個時區“馬德里”,而不是我當前的時區。
有沒有辦法使這項工作?
謝謝!
這是這個django 時區的來源
將以下中間件添加到 MIDDLEWARE:
import pytz
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
tzname = request.session.get('django_timezone')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
return self.get_response(request)
創建一個可以設置當前時區的視圖:
from django.shortcuts import redirect, render
def set_timezone(request):
if request.method == 'POST':
request.session['django_timezone'] = request.POST['timezone']
return redirect('/')
else:
return render(request, 'template.html', {'timezones': pytz.common_timezones})
在 template.html 中包含一個表單,該表單將發布到此視圖:
{% load tz %}
{% get_current_timezone as TIME_ZONE %}
<form action="{% url 'set_timezone' %}" method="POST">
{% csrf_token %}
<label for="timezone">Time zone:</label>
<select name="timezone">
{% for tz in timezones %}
<option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option>
{% endfor %}
</select>
<input type="submit" value="Set">
</form>
表單中的時區感知輸入¶ 當您啟用時區支持時,Django 解釋在當前時區中 forms 中輸入的日期時間,並在 clean_data 中返回感知日期時間對象。
如果當前時區對不存在或不明確的日期時間引發異常,因為它們屬於 DST 轉換(pytz 提供的時區會這樣做),則此類日期時間將被報告為無效值。
模板中的時區感知 output¶ 當您啟用時區支持時,Django 在模板中呈現時將感知日期時間對象轉換為當前時區。 這與格式本地化非常相似。
警告
Django 不會轉換幼稚的日期時間對象,因為它們可能不明確,並且因為啟用時區支持時您的代碼不應生成幼稚的日期時間。 但是,您可以使用下面描述的模板過濾器強制轉換。
轉換為本地時間並不總是合適的——您可能會為計算機而不是人類生成 output。 tz 模板標簽庫提供的以下過濾器和標簽允許您控制時區轉換。
模板標簽¶ localtime¶ 啟用或禁用將感知日期時間對象轉換為包含塊中的當前時區。
就模板引擎而言,此標記與 USE_TZ 設置具有完全相同的效果。 它允許對轉換進行更細粒度的控制。
要激活或停用模板塊的轉換,請使用:
{% load tz %}
{% localtime on %}
{{ value }}
{% endlocaltime %}
{% localtime off %}
{{ value }}
{% endlocaltime %}
筆記
USE_TZ 的值在 {% localtime %} 塊內不受尊重。
timezone¶ 設置或取消設置包含塊中的當前時區。 未設置當前時區時,將應用默認時區。
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
{% timezone None %}
Server time: {{ value }}
{% endtimezone %}
get_current_timezone¶ 您可以使用 get_current_timezone 標簽獲取當前時區的名稱:
{% get_current_timezone as TIME_ZONE %}
或者,您可以激活 tz() 上下文處理器並使用 TIME_ZONE 上下文變量。
來自https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/
from django.utils import timezone
now = timezone.now()
如果將來有人想要,這對我有用。
import datetime
import pytz
tz = pytz.timezone('Asia/Colombo')
current_time = datetime.datetime.now(tz)
您可以在此處獲取 pytz 的本地時區列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.