我需要在代码中为系统日期时间设置一个值。在django应用程序的settings.py中,我注释了TIME_ZONE和USE_TZ= True。
在我的文件中,代码如下所示:
import datetime
checkedin_dt = datetime.datetime.now()
logger.info(checkedin_dt) # -- gives me a value that is utc-5:00然而,当我在python终端中运行同样的东西时,它给出了正确的systemdatetime。我希望我的代码在不在settings.py中设置任何特定时区的情况下获取systemdatetime
你知道为什么这在代码中不起作用吗?数据库是sqlite,应用程序是django应用程序。
发布于 2020-06-25 23:01:43
设置USE_TZ = True并使用timezone()
from django.utils import timezone
checkedin_dt = timezone.now()文档:https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/
发布于 2020-06-26 17:12:47
Django不包括确定系统时区的方法,但您可以使用tzlocal包来确定。
我自己从来没有尝试过,但我认为你可以通过在设置文件中执行以下操作来获得你想要的:
from tzlocal import get_localzone
TIME_ZONE = get_localzone().zone如果不能确定时区的名称,它仍然可能失败,因为TIME_ZONE必须是字符串名。
https://stackoverflow.com/questions/62576596
复制相似问题