2

I store a datetime in database (SQLite). I save python datetime objects with UTC timezone (so they are aware) in my models. When I check the database I literally see 2018-02-28 00:00:00. When I fetch data from database I see:

>>> Price.objects.last().datetime.timetuple()
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=59, tm_isdst=0)

So far so good (time is really a midnight). But once I try to divide UNIX timestamp I get wrong result:

>>> time.mktime(Price.objects.last().datetime.timetuple()) / 3600 / 24
17589.958333333332

When I adjust the timestamp with +1 hour it's finally right.

>>> (time.mktime(Price.objects.last().datetime.timetuple()) + 3600) / 3600 / 24
17590.0

What do I do wrong? Why struct_time shows hours=0 and minutes=0 but once I call time.mktime it gets wrong?

n1_
  • 4,227
  • 4
  • 34
  • 35

2 Answers2

0

The function mktime take time in local time, so I assume your computer is in a UTC+1 timezone (without considering summer time, which is considered by mktime).

See Python - calendar.timegm() vs. time.mktime() on how to "make time" with UTC (GMT) times.

Giacomo Catenazzi
  • 8,519
  • 2
  • 24
  • 32
0

When you save your model, do you use django timezone class ?

from django.utils import timezone now = timezone.now()

and put in settings.py :

USE_TZ=True

Source here : https://docs.djangoproject.com/fr/2.0/topics/i18n/timezones/#naive-and-aware-datetime-objects

I think your problem is what you put in your model.

MaximeK
  • 2,039
  • 1
  • 10
  • 16
  • As I wrote my data are 100% ok in database. The issue is when I calc unix timestamp. – n1_ Mar 27 '18 at 16:25