Django Code Snippets

Powered by PythonAnywhere and Django 1.8.6

Django DateTime

Date Added: Nov. 12, 2015, 3:56 p.m.

Author: craigderington



from dateutil.relativedelta import relativedelta
from django import template

register = template.Library()

@register.filter
def adjust(value, arg):
  """Adjusts the datetime object by the argument and returns the new datetime for formatting

    @note: Uses relativedelta to adjust the date object

    Usage: {{ dateobject|adjust:"weeks=1" }}, or
           {{ dateobject|adjust:"weeks=1, days=2"|date:"Y m d" }}
  """
  args = dict(tuple(e.split('=')) for e in arg.split(', '))

  for k, v in args.iteritems():
    args[k] = int(v) # Convert all values to integers

  return value + relativedelta(**args)


 

Tags: django, python

Return to List