Reputation: 2391
I've got a Django app (running on Heroku with Postgres) with a simple form that contains a DateTimeField():
class Response(models.Model):
'''
Model serves to record a users response to a given question on a given
questionnaire.
'''
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
default=None,
db_index=True,
)
date = models.DateTimeField(
blank=False,
auto_now_add=True,
db_index=True,
help_text=(
"Date on which question was answered."
)
)
From what I understand, my date
field should get populated automatically with the current datetime
For DateTimeField: default=timezone.now - from django.utils.timezone.now()
-- ref
Furthermore, it should be a UTC timestamp
If USE_TZ is True, this will be an aware datetime representing the current time in UTC.
-- ref
My settings.py has
TIME_ZONE = 'UTC'
USE_TZ = True
And I've got some middleware that sets current time zone to CST:
from django.utils import timezone
import pytz
class TimezoneMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
timezone.activate(pytz.timezone('America/Chicago'))
else:
timezone.deactivate()
I have some debugging print statements used right before the form submit [print(now(), localtime(now()), get_current_timezone())
] to validate that now()
is actually UTC.
When I submit my form I'm seeing:
2018-03-06T16:56:23.569311+00:00 app[web.1]: 2018-03-06 16:56:23.569131+00:00 2018-03-06 10:56:23.569145-06:00 America/Chicago
however the database stores 2018-03-06 10:56:23
How can I ensure that my submitted timestamps properly get converted to UTC?
Upvotes: 0
Views: 318
Reputation: 48902
however the database stores
2018-03-06 10:56:23
I would look into that more carefully; depending on how you're getting that value, it may or may not be what's actually stored in the database. Database drivers (and of course Django itself) can change the timezone on the way from the database. Check the timezone of that value if it's coming through the database driver and you might find that you don't have a problem after all.
Upvotes: 1