Skip to main content

Some useful datetime functions for Django

Project description


These utility functions are helpful in handling dates, datetimes, and timezones in Django.


Let's say you have the following in your Django

USE_TZ = True

Now let's attempt to write our own tomorrow() function.

from datetime import timedelta
from django.utils.timezone import now

def tomorrow():
  # Subtle bug! Django's now() function returns a timezone enabled datetime
  # in UTC, regardless of the TIME_ZONE setting. If it's 11 Wednesday
  # MORNING in New York, this function will work. But if it's 11 Wednesday
  # NIGHT in New York, the UTC timezone is already in Thursday, so in that
  # case this code will return Friday.
  return now().date() + timedelta(days=1)

Here's one way to fix the problem.

from datetime import timedelta
from djavedt import now

def tomorrow():
  # djavedt's now() function returns a timezone enabled datetime in the
  # timezone of the TIME_ZONE setting, which is EST in our example. So this
  # function will work as expected at 11PM in New York.
  return now().date() + timedelta(days=1)

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for djavedt, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size djavedt-1.0.0-py3-none-any.whl (5.5 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size djavedt-1.0.0.tar.gz (4.5 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page