Skip to main content
 首页 » 编程设计

python之Django: activate() 没有显示效果

2024年08月26日31bjzhanghao

我在 python manager.py shell 中有以下行:

>>> import pytz 
>>> from django.utils import timezone 
>>> zone = "Asia/Kolkata" 
>>> timezone.activate(pytz.timezone(zone)) 
>>> timezone.now() 
datetime.datetime(2014, 12, 17, 1, 52, 0, 411937, tzinfo=<UTC>) 

但我得到的输出仍然使用 UTC。不应该改成“Asia/Kolkata”吗?

更新

如果我使用下面 dazedconfused 建议的命令:

zone = "Asia/Kolkata" 
if zone: 
    timezone.activate(pytz.timezone(zone)) 
else: 
    timezone.deactivate() 
utc_date = datetime.utcnow() 
aware_date = timezone.make_aware(utc_date, timezone.utc) 
l_time = timezone.localtime(aware_date, timezone.get_current_timezone()) 

现在当我尝试将它保存到我的数据库(Mongodb on Mongolab)时,它被保存为 UTC 我的数据库中有一个 DateTimeField。

虽然当我将它保存为一个简单的字符串时,它会保存在当前时区“亚洲/加尔各答”输出为字符串:2014-12-17 11:01:53.028852+05:30

请您参考如下方法:

它实际上成功地将当前时区设置为“Asia/Kolkata”

您可以通过以下方式验证:

... 
>>> timezone.get_current_timezone_name() 
'Asia/Kolkata' 

来自django documentation :

now():

Returns a datetime that represents the current point in time. Exactly what’s returned depends on the value of USE_TZ:

  • If USE_TZ is False, this will be a naive datetime (i.e. a datetime without an associated timezone) that represents the current time in the system’s local timezone.

  • If USE_TZ is True, this will be an aware datetime representing the current time in UTC. Note that now() will always return times in UTC regardless of the value of TIME_ZONE; you can use localtime() to convert to a time in the current time zone.

因此,如果您系统的本地时区是“亚洲/加尔各答”,您可以在 settings.py 中将 USE_TZ 设置为 False 并且timezone.now() 将返回您想要的内容。

或者,您必须使用 localtime()将时区转换为您的时区(从您的 shell 结果继续):

... 
>>> import datetime 
>>> utc_date = datetime.datetime.utcnow() 
>>> aware_date = timezone.make_aware(utc_date, timezone.utc) 
>>> timezone.localtime(aware_date, timezone.get_current_timezone()) 
datetime.datetime(2014, 12, 17, 8, 0, 36, 598113, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>) 

最后,here是 make_aware() 函数的文档