Insert a Timezone-Aware Datetime in Django

In some situations, it is necessary to insert a specific datetime value into the database instead of relying on automatic timestamps. When working with Django and timezones enabled, datetimes should be timezone-aware to avoid inconsistencies. Assume the following Time model:

class Time(models.Model):
    datetime = models.DateTimeField(blank = True, null=True)

    def __str__(self):
        return str(self.datetime)

 

 

Configuring TIME_ZONE

The project timezone can be configured in settings.py using the TIME_ZONE setting, for example "Europe/Lisbon".
For a complete list of timezone identifiers, see: 
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

TIME_ZONE = "Europe/Lisbon"
USE_TZ = True

 

 

Inserting a Specific Datetime

The make_aware() function converts a naive datetime into a timezone-aware datetime using the specified timezone.

from django.views.generic import TemplateView
from django.utils import timezone
from datetime import datetime
from polls.models import Time

class index(TemplateView):
    template_name = 'polls/index.html'

    def get_context_data(self, **kwargs):

        date = datetime(2022, 6, 23, 17, 34, 30)

        Time.objects.create(
            datetime=timezone.make_aware(date)
        )

        return super().get_context_data(**kwargs)