Reputation: 2738
I have next model:
class People(models.Model):
name = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
_date=models.DateTimeField()
In views.py
-When I try this one:
p = People(name='foo', lastname='bar', _date=datetime.now())
p.save()
it returns current time: 2012-10-31 17:33:10.152323
But, when I check my database for this record it shows:
name lastname _date
foo bar 2012-10-31 21:33:10
Why this(two different time) happens?
Edit: (it is 4 hours difference): 2012-10-31 17:33:10.152323 and 2012-10-31 21:33:10
Upvotes: 0
Views: 2858
Reputation: 1684
Even I was facing the same issue. This is because according to the django documentation
When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.
Solution to this problem is writing a function that converts time stored in database to your local time.
from django.utils import timezone
import pytz
def get_localtime(utctime):
utc = utctime.replace(tzinfo=pytz.UTC)
localtz = utc.astimezone(timezone.get_current_timezone())
return localtz
Now you can
now = get_localtime(datetime.now())
p = People(name='foo', lastname='bar', _date=now)
p.save()
Upvotes: 1
Reputation: 2569
Django uses timezones to store DatetimeFields
into your database. This is why you supplied a TIME_ZONE
in your settings.
You can read more about this here: https://docs.djangoproject.com/en/dev/topics/i18n/timezones/
If you want to supply your fields with a non naive datetime, you have to use:
now = datetime.utcnow().replace(tzinfo=timezone('Your/Timezone'))
Timezones can be found here: http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
Upvotes: 2