Skip to content

Instantly share code, notes, and snippets.

@ncherro
Created April 10, 2013 20:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncherro/5358040 to your computer and use it in GitHub Desktop.
Save ncherro/5358040 to your computer and use it in GitHub Desktop.
django template tag - format date range
from django import template
register = template.Library()
@register.simple_tag
def format_date_range(date_from, date_to, separator=" - ",
format_str="%B %d, %Y", year_f=", %Y", month_f="%B", date_f=" %d"):
""" Takes a start date, end date, separator and formatting strings and
returns a pretty date range string
"""
if (date_to and date_to != date_from):
from_format = to_format = format_str
if (date_from.year == date_to.year):
from_format = from_format.replace(year_f, '')
if (date_from.month == date_to.month):
to_format = to_format.replace(month_f, '')
return separator.join((date_from.strftime(from_format), date_to.strftime(to_format)))
else:
return date_from.strftime(format_str)
@Lh4cKg
Copy link

Lh4cKg commented May 18, 2015

how it works? can u show exaple html code

@LastDreamer
Copy link

thx

@yannhowe
Copy link

Thanks this was really helpful!

For those new to custom template tags (like me)

Required reading:
https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/
https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#simple-tags

  • place code in yourtagfile.py in templatetags directory with init.py
  • Remember to {% load yourtagfile.py %} in templates that require custom template tag
  • example use {% format_date_range event.date_start event.date_end %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment