Add a new filter: strftime. Use the well known function to format a date output.

pull/12251/head
Yannig Perré 9 years ago
parent 5adcd7054b
commit 3f5b304fc2

@ -461,6 +461,25 @@ To escape special characters within a regex, use the "regex_escape" filter::
# convert '^f.*o(.*)$' to '\^f\.\*o\(\.\*\)\$'
{{ '^f.*o(.*)$' | regex_escape() }}
.. versionadded:: 2.0
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
A few useful filters are typically added with each new Ansible release. The development documentation shows
how to extend Ansible filters by writing your own as plugins, though in general, we encourage new ones
to be added to core so everyone can make use of them.

@ -34,6 +34,7 @@ from functools import partial
import operator as py_operator
from random import SystemRandom, shuffle
import uuid
import time
import yaml
from jinja2.filters import environmentfilter
@ -99,6 +100,15 @@ def bool(a):
else:
return False
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 pipes.quote(a)
@ -283,6 +293,9 @@ class FilterModule(object):
# value as boolean
'bool': bool,
# date formating
'strftime': strftime,
# quote string for shell usage
'quote': quote,

@ -68,3 +68,15 @@
- '"0.10 GB" == 102400000|human_readable(unit="G")'
- '"0.10 Gb" == 102400000|human_readable(isbits=True, unit="G")'
- name: Check strftime
tags: "strftime"
assert:
that:
# epoch(1111111111) = 2005-03-18
- '"2005" == "%Y"|strftime(1111111111)'
- '"03" == "%m"|strftime(1111111111)'
- '"18" == "%d"|strftime(1111111111)'
# epoch(0) = 1970-01-01
- '"1970" == "%Y"|strftime(0)'
- '"01" == "%m"|strftime(0)'
- '"01" == "%d"|strftime(0)'

Loading…
Cancel
Save