Skip to main content

Some useful datetime functions for Django

Project description

Introduction

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

Examples

Let's say you have the following in your Django settings.py

TIME_ZONE = 'EST'
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.

Source Distribution

djavedt-1.0.0.tar.gz (4.5 kB view hashes)

Uploaded source

Built Distribution

djavedt-1.0.0-py3-none-any.whl (5.5 kB view hashes)

Uploaded py3

Supported by

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