import datetime from django.db import models from django.utils import timezone from django.conf import settings class DateTimePGUTCField(models.DateTimeField): """ PostgreSQL has a native timestamp type that stores UTC datetime but witout timezone info, so we need to convert it in Python. """ def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.postgresql': return 'timestamp' raise TypeError('this field only works with PostgreSQL') def from_db_value(self, value, expression, connection): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_naive(value): return value.replace(tzinfo=datetime.timezone(datetime.timedelta(hours=0))) return value return super(DateTimePGUTCField, self).to_python(value)