import datetime from django import template register = template.Library() if 1: # explicit tag name @register.tag('current_time') class CurrentTimeNode(template.Node): def __init__(self, parser, token): try: # split_contents() knows not to split quoted strings. tag_name, format_string = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name self.format_string = str(format_string[1:-1]) def render(self, context): return datetime.datetime.now().strftime(self.format_string) else: # implicit tag name @register.tag class current_time(template.Node): def __init__(self, parser, token): try: # split_contents() knows not to split quoted strings. tag_name, format_string = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name self.format_string = str(format_string[1:-1]) def render(self, context): return datetime.datetime.now().strftime(self.format_string)