import re
from django import template
register = template.Library()
@register.simple_tag
def format_date_range(from_date, to_date):
"""
>>> import datetime
>>> format_date_range(datetime.date(2009,1,15), datetime.date(2009,1,20))
'15. - 20.01.2009.'
>>> format_date_range(datetime.date(2009,1,15), datetime.date(2009,2,20))
'15.01. - 20.02.2009.'
>>> format_date_range(datetime.date(2009,1,15), datetime.date(2010,2,20))
'15.01.2009. - 20.02.2010.'
>>> format_date_range(datetime.date(2009,1,15), datetime.date(2010,1,20))
'15.01.2009. - 20.01.2010.'
Use in django templates:
{% load date_range %}
{% format_date_range exhibition.start_on exhibition.end_on %}
"""
from_format = to_format = '%d.%m.%Y.'
if (from_date.year == to_date.year):
from_format = from_format.replace('%Y.', '')
if (from_date.month == to_date.month):
from_format = from_format.replace('%m.', '')
return " - ".join((from_date.strftime(from_format), to_date.strftime(to_format), ))
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Comments
Try it with same month and different year. Like this:
Is it what you mean? Maybe it will better to put second if inside first if?
#
Astur, you are right - I updated code to reflect this. Thanks
#