[Django]-Get local system time in Django

11👍

You’d want to use django.utils.timezone, specifically:

from django.utils.timezone import localtime, now

# get now datetime based upon django settings.py TZ_INFO
localtime(now())

1👍

From django docs:

How do I interact with a database that stores datetimes in local time?

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.

Set USE_TZ=True so that django would use a timezone-aware datetime objects internally.

Set TIME_ZONE in the DATABASES setting, to accommodate the legacy databases. Django will convert your datetimes to the appropriate timezone automatically i.e., to get the current time it is enough:

from django.utils import timezone

now = timezone.now()

Note: datetime.now() returns a naive datetime object. Don’t use it.

👤jfs

Leave a comment