Login

Date/time util template filters

Author:
marinho
Posted:
November 15, 2007
Language:
Python
Version:
.96
Tags:
date time template-filters
Score:
1 (after 1 ratings)

Explanations:

  • the series "is_*_of" was created 'cos it's easier write: {% if 10|is_day_of:date and user %} than write: {% ifequal date.day 10 %}{% if user %}...
  • the series "inc/dec" is not complete, but can the extended to day, hour, minute, etc as you needs. It's util to inc 10 months since 05/31/2006 by example and get a 2007's date :)

Setup:

Insert the snippet into an_app/templatetags/datetimeutils.py.

Use in template:

{% load datetimeutils %} and use filters as following:

  • {{ 30|is_day_of:a_date_time_variable }}
  • {{ 11|is_month_of:a_date_time_variable }}
  • {{ 2006|is_year_of:a_date_time_variable }}
  • {{ 58|is_minute_of:a_date_time_variable }}
  • {{ 23|is_hour_of:a_date_time_variable }}
  • {{ a_date_time_variable|dec_year:2 }}
  • {{ a_date_time_variable|dec_month:2 }}
  • {{ a_date_time_variable|inc_year:2 }}
  • {{ a_date_time_variable|inc_month:2 }}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.template import Library
from datetime import datetime, timedelta

@register.filter
def is_day_of(value,arg):
    return (arg and value) and arg.day == int(value)

@register.filter
def is_month_of(value,arg):
    return (arg and value) and arg.month == int(value)

@register.filter
def is_year_of(value,arg):
    return (arg and value) and arg.year == int(value)

@register.filter
def is_hour_of(value,arg):
    return (arg and value) and arg.hour == int(value)

@register.filter
def is_minute_of(value,arg):
    return (arg and value) and arg.minute == int(value)

@register.filter
def dec_year(value,arg):
    delta = type(arg) != types.IntType and int(arg) or arg
    return value - timedelta(365 * delta)

@register.filter
def dec_month(value,arg):
    delta = type(arg) != types.IntType and int(arg) or arg
    return value - timedelta(30 * delta)

@register.filter
def inc_year(value,arg):
    delta = type(arg) != types.IntType and int(arg) or arg
    return value + timedelta(365 * delta)

@register.filter
def inc_month(value,arg):
    delta = type(arg) != types.IntType and int(arg) or arg
    return value + timedelta(30 * delta)

More like this

  1. Template filters utils by marinho 7 years, 5 months ago
  2. simple text image view by derelm 8 years, 1 month ago
  3. Template filter that divides a list into exact columns by davmuz 3 years, 2 months ago
  4. A simple rest template filter by marinho 7 years, 5 months ago
  5. Fuzzy Date Diff Template Filter by zain 6 years, 1 month ago

Comments

Please login first before commenting.