From 3358abcf49d41deeec3139dc5527e5aad6d3eb49 Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Fri, 21 Apr 2017 14:48:45 -0400 Subject: [PATCH] Add a new filter: strftime. Use the well known function to format a date output. (#23832) (cherry picked from commit 3f5b304fc28b6c34df9ea6a4c3531dc422ce198b) rebased for @yannig --- docs/docsite/rst/playbooks_filters.rst | 18 ++++++++++++++++++ lib/ansible/plugins/filter/core.py | 16 +++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/docsite/rst/playbooks_filters.rst b/docs/docsite/rst/playbooks_filters.rst index be8564aa98b..2a6c38f205d 100644 --- a/docs/docsite/rst/playbooks_filters.rst +++ b/docs/docsite/rst/playbooks_filters.rst @@ -644,6 +644,24 @@ To always exhaust all list use ``zip_longest``:: debug: msg="{{ [1,2,3]|zip_longest(['a','b','c','d','e','f'], [21, 22, 23], fillvalue='X')|list }}" +.. versionadded:: 2.4 +To format a date using a string (like with the shell date command), use the "strftime" filter:: + + # Display year-month-day + {{ '%Y-%m-%d' | strftime }} + + # Display hour:min:sec + {{ '%H:%M:%S' | strftime }} + + # Use ansible_date_time.epoch fact + {{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }} + + # Use arbitrary epoch value + {{ '%Y-%m-%d' | strftime(0) }} # => 1970-01-01 + {{ '%Y-%m-%d' | strftime(1441357287) }} # => 2015-09-04 + +.. note:: To get all string possibilities, check https://docs.python.org/2/library/time.html#time.strftime + Debugging Filters ````````````````` diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 89b264bcd75..e82061a51d2 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -30,13 +30,15 @@ import os.path import re import string import sys +import time import uuid +import yaml + from collections import MutableMapping, MutableSequence from datetime import datetime from functools import partial from random import Random, SystemRandom, shuffle -import yaml from jinja2.filters import environmentfilter, do_groupby as _do_groupby try: @@ -121,6 +123,15 @@ def to_datetime(string, format="%Y-%d-%m %H:%M:%S"): return datetime.strptime(string, format) +def strftime(string_format, second = None): + ''' return a date string using string. See https://docs.python.org/2/library/time.html#time.strftime for format ''' + if second is not None: + try: + second = int(second) + except: + raise errors.AnsibleFilterError('Invalid value for epoch value (%s)' % second) + return time.strftime(string_format, time.localtime(second)) + def quote(a): ''' return its argument quoted for shell usage ''' return shlex_quote(a) @@ -510,6 +521,9 @@ class FilterModule(object): # value as boolean 'bool': to_bool, + # date formating + 'strftime': strftime, + # quote string for shell usage 'quote': quote,