Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime.now() returns wrong day in Django application

Tags:

python

django

My Django application (nginx, uwsgi stack) requests the current day by calling datetime.now():

def get_drinks(request, drink_type):
    current_day = datetime.today().strftime("%w")
    current_day_string = datetime.today().strftime("%A")

And I show the current day on my website. For some bizarre reason, it is returning Friday, instead of Thursday (today). My server time is:

server:~$ date
Thu Apr  9 18:51:02 PDT 2015

And when I run datetime.now() in the python shell, I get Thursday as well:

>>> import datetime
>>> datetime.datetime.today().strftime("%A")
'Thursday'

What's the issue here?

like image 915
farbodg Avatar asked Dec 24 '22 20:12

farbodg


2 Answers

datetime.datetime.now() is not aware of timezone so gets the current time in system's local timezone. You should set TIME_ZONE to America/Los_Angeles (PST/PDT) and USE_TZ to True in your settings.py file so that all date values created within your application are always timezone aware as long as you import from django.utils.timezone.

Please see the timezone documentation for more information.

TIME_ZONE = "America/Los_Angeles"
USE_TZ = True

>>> from django.utils import timezone

>>> print timezone.now()
datetime.datetime(2015, 4, 10, 2, 17, 10, 839067, tzinfo=<UTC>)

>>> print timezone.localtime(timezone.now())
datetime.datetime(2015, 4, 9, 19, 17, 10, 839067, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
like image 164
Ozgur Vatansever Avatar answered Dec 27 '22 11:12

Ozgur Vatansever


You should change Django's locale setting.

here is another question and answer for same problem.

System date formatting not picking up django locale

like image 22
tanaydin Avatar answered Dec 27 '22 11:12

tanaydin