0

I'm in the situation where I use django (2.0.7) to deal with multiples databases:

  1. database_A: without timezone;
  2. database_B: with timezone 'Europe/Paris';

settings.py

USE_TZ = True
TIME_ZONE = 'Europe/Paris'

DATABASES = {
  'database_A': {
     'NAME': ...
     'PASSWORD': ... etc.
     'TIME_ZONE': None,
     # still raise RuntimeWarning; received a naive datetime while time zone support is active.
},
  'database_B': {
    'NAME': ..., etc.
}

on models of database A

class Something(models.Model):
   date_creation = models.DateTimeField()

   def save(self, *args, **kwargs):
       if self._state.adding is True:
          self.date_creation = timezone.datetime.now()  # naive 

       print("BEFORE SAVE")
       print(self.date_creation)

       super(Something, self).save(*args, **kwargs)

       print("AFTER SAVE")
       print(self.date_creation)

       print("AFTER REFRESH")
       self.refresh_from_db()
       print(self.date_creation)

I get the following result

 BEFORE SAVE
 2019-11-04 11:44:35.233876
 AFTER SAVE
 2019-11-04 11:44:35.233929
 AFTER REFRESH
 2019-11-04 10:44:35.23392             # 10:44:35  , what's wrong ô_O ?

I have the same 1 hour difference between Europe/Paris and UTC.

import pytz
from datetime import datetime
datetime.now(tz=pytz.timezone('Europe/Paris')), timezone.now()

(datetime.datetime(2019, 11, 4, 12, 10, 55, 320028, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>),
 datetime.datetime(2019, 11, 4, 11, 10, 55, 320077, tzinfo=<UTC>))

So, I think PostgreSQL is using UTC to save my naive datetime considered as timezone aware datetime ?

In database I have the following time

\d something_table
date_creation           | timestamp without time zone | non NULL Par defaut, now()

 SELECT NOW();
              now
-------------------------------
 2019-11-04 11:45:48.907105+01             # consider delay, changing terminal to launch query;
(1 ligne)

Django documentation about multiples databases and timezones says:

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.

Is Django or PostgreSQL saving localtime into UTC even if time_zone is None ? Any idea how to solve it ? (I can't change database schema T_T)

user2652620
  • 464
  • 2
  • 17

1 Answers1

0

answering my own question.

To deal with datetime without timezone, the datetimefield must be replaced with charfield.

user2652620
  • 464
  • 2
  • 17