Reputation: 384
I have a Django app that interacts heavily with other legacy databases. These other databases all use local time, not UTC. I understand Django's time zone support as well as the recommendation to always use UTC time except with interacting with a user. In this case, I really just need Django to give me the system date/time.
In settings.py I have
USE_TZ = False
And when I run date
from the linux command line I get (for example):
Tue Mar 15 17:03:42 MDT 2016
Also when I open a regular (non-django) python shell and run
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:
'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?
Upvotes: 3
Views: 9338
Reputation: 414139
From 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.
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.
Set USE_TZ=True
so that django would use a timezone-aware datetime objects internally.
Set TIME_ZONE
in the DATABASES
setting, to accommodate the legacy databases. Django will convert your datetimes to the appropriate timezone automatically i.e., to get the current time it is enough:
from django.utils import timezone
now = timezone.now()
Note: datetime.now()
returns a naive datetime object. Don't use it.
Upvotes: 1
Reputation: 20770
You'd want to use django.utils.timezone
, specifically:
from django.utils.timezone import localtime, now
# get now datetime based upon django settings.py TZ_INFO
localtime(now())
Upvotes: 11