[英]Get local system time in Django
I have a Django app that interacts heavily with other legacy databases. 我有一个Django应用程序,可以与其他遗留数据库进行大量交互。 These other databases all use local time, not UTC.
这些其他数据库都使用本地时间,而不是UTC。 I understand Django's time zone support as well as the recommendation to always use UTC time except with interacting with a user.
我理解Django的时区支持以及除了与用户交互之外总是使用UTC时间的建议。 In this case, I really just need Django to give me the system date/time.
在这种情况下,我真的只需要Django给我系统日期/时间。
In settings.py I have 在settings.py我有
USE_TZ = False
And when I run date
from the linux command line I get (for example): 当我从linux命令行运行
date
时(例如):
Tue Mar 15 17:03:42 MDT 2016
Also when I open a regular (non-django) python shell and run 当我打开常规(非django)python shell并运行时
import datetime
str(datetime.datetime.now())
I get 我明白了
'2016-03-15 17:04:55.182283'
But when I run the same commands from a Django shell (python manage.py shell)
I get a time one hour earlier: 但是当我从Django shell
(python manage.py shell)
运行相同的命令时,我会在一小时前得到一个时间:
'2016-03-15 16:07:10.949269'
Is there some way that I can get a datetime object that has exactly the system time, ignoring any other time zone magic? 有什么方法可以让我获得一个具有完全系统时间的日期时间对象,忽略任何其他时区魔术?
You'd want to use django.utils.timezone
, specifically: 你想使用
django.utils.timezone
,具体来说:
from django.utils.timezone import localtime, now
# get now datetime based upon django settings.py TZ_INFO
localtime(now())
From django docs : 来自django docs :
How do I interact with a database that stores datetimes in local time?
如何与以当地时间存储日期时间的数据库进行交互?
Set the TIME_ZONE option to the appropriate time zone for this database in the DATABASES setting.
在DATABASES设置中将TIME_ZONE选项设置为此数据库的相应时区。
This is useful for connecting to a database that doesn't support time zones and that isn't managed by Django when USE_TZ is True.
这对于连接到不支持时区且在USE_TZ为True时不由Django管理的数据库很有用。
Set USE_TZ=True
so that django would use a timezone-aware datetime objects internally. 设置
USE_TZ=True
以便django在内部使用时区感知日期时间对象。
Set TIME_ZONE
in the DATABASES
setting, to accommodate the legacy databases. 在
DATABASES
设置中设置TIME_ZONE
,以容纳旧数据库。 Django will convert your datetimes to the appropriate timezone automatically ie, to get the current time it is enough: Django会自动将您的日期时间转换为适当的时区,即获取当前时间就足够了:
from django.utils import timezone
now = timezone.now()
Note: datetime.now()
returns a naive datetime object. 注意:
datetime.now()
返回一个天真的日期时间对象。 Don't use it. 不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.