summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoman Belyakovsky <ihryamzik@gmail.com>2016-09-01 03:51:03 +0400
committerMichael Scherer <mscherer@users.noreply.github.com>2016-09-01 01:51:03 +0200
commitd80d986a38c0cdaf7a29e82e5d0d9873e37dc9f0 (patch)
tree93be1ee30458990747492b7e2b6fb1a803012269
parent2ffb136b3febe6efe09d0c8b745b7cbbf5c747d3 (diff)
downloadansible-d80d986a38c0cdaf7a29e82e5d0d9873e37dc9f0.tar.gz
Added to_datetime filter (#17145)
* Added to_datetime filter * Added to_datetime filter documentation
-rw-r--r--docsite/rst/playbooks_filters.rst9
-rw-r--r--lib/ansible/plugins/filter/core.py8
2 files changed, 14 insertions, 3 deletions
diff --git a/docsite/rst/playbooks_filters.rst b/docsite/rst/playbooks_filters.rst
index 0882c960d9..8b2bb062e3 100644
--- a/docsite/rst/playbooks_filters.rst
+++ b/docsite/rst/playbooks_filters.rst
@@ -412,7 +412,7 @@ Other Useful Filters
To add quotes for shell usage::
- - shell: echo {{ string_value | quote }}
+ - shell: echo {{ string_value | quote }}
To use one value on true and another on false (new in version 1.9)::
@@ -510,6 +510,11 @@ To make use of one attribute from each item in a list of complex variables, use
# get a comma-separated list of the mount points (e.g. "/,/mnt/stuff") on a host
{{ ansible_mounts|map(attribute='mount')|join(',') }}
+To get date object from string use the `to_datetime` filter, (new in version in 2.2):
+
+ # get amount of seconds between two dates, default date format is %Y-%d-%m %H:%M:%S but you can pass your own one
+ {{ (("2016-08-04 20:00:12"|to_datetime) - ("2015-10-06"|to_datetime('%Y-%d-%m'))).seconds }}
+
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.
@@ -536,5 +541,3 @@ to be added to core so everyone can make use of them.
Have a question? Stop by the google group!
`irc.freenode.net <http://irc.freenode.net>`_
#ansible IRC chat channel
-
-
diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py
index dcb496b0f6..0889cee591 100644
--- a/lib/ansible/plugins/filter/core.py
+++ b/lib/ansible/plugins/filter/core.py
@@ -34,6 +34,7 @@ import hashlib
import string
from functools import partial
from random import SystemRandom, shuffle
+from datetime import datetime
import uuid
import yaml
@@ -116,6 +117,10 @@ def to_bool(a):
else:
return False
+def to_datetime(string, format="%Y-%d-%m %H:%M:%S"):
+ return datetime.strptime(string, format)
+
+
def quote(a):
''' return its argument quoted for shell usage '''
return pipes.quote(a)
@@ -393,6 +398,9 @@ class FilterModule(object):
'to_nice_yaml': to_nice_yaml,
'from_yaml': yaml.safe_load,
+ #date
+ 'to_datetime': to_datetime,
+
# path
'basename': partial(unicode_wrap, os.path.basename),
'dirname': partial(unicode_wrap, os.path.dirname),