Login

Datetime adjuster for Django Templates

Author:
McAnix
Posted:
July 22, 2015
Language:
Python
Version:
1.4
Score:
1 (after 1 ratings)

The filter is specific to datetime objects and no allowance has been made to convert strings or epoch times. Also no type checking is performed so misuse will result in an error.

To use include the above snippet in a file called templatetags/customfilters.py or append to existing filters file then load:

{% load customfilters %}

in your template, then to use it:

{{ dateobject|adjust:"months=1"|date:"Y/m/d" }}

To push the dateobject forward by a month, or:

{{ dateobject|adjust:"weeks=-1"|date:"Y/m/d" }}

To push the dateobject back a week, or:

{{ dateobject|adjust:"years=1, months=2"|date:"Y/m/d" }}

To push the dateobject forward by a year and 2 months

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.