From c3a3bc1d0ddf58282b3b41dd376297f513c8fb53 Mon Sep 17 00:00:00 2001 From: Will Thames Date: Fri, 15 Apr 2022 02:35:19 +1000 Subject: [PATCH] Allow strftime to display time in UTC (#70351) --- changelogs/fragments/strftime-in-utc.yml | 2 ++ docs/docsite/rst/user_guide/playbooks_filters.rst | 7 +++++++ lib/ansible/plugins/filter/core.py | 8 ++++++-- 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 changelogs/fragments/strftime-in-utc.yml diff --git a/changelogs/fragments/strftime-in-utc.yml b/changelogs/fragments/strftime-in-utc.yml new file mode 100644 index 00000000000..5b6237d5506 --- /dev/null +++ b/changelogs/fragments/strftime-in-utc.yml @@ -0,0 +1,2 @@ +minor_changes: + - Provide a `utc` option for strftime to show time in UTC rather than local time diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index 040fa7978e4..4d37b1c9e36 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -2117,6 +2117,13 @@ To format a date using a string (like with the shell date command), use the "str {{ '%Y-%m-%d' | strftime(0) }} # => 1970-01-01 {{ '%Y-%m-%d' | strftime(1441357287) }} # => 2015-09-04 +.. versionadded:: 2.13 + +strftime takes an optional utc argument, defaulting to False, meaning times are in the local timezone:: + + {{ '%H:%M:%S' | strftime }} # time now in local timezone + {{ '%H:%M:%S' | strftime(utc=True) }} # time now in UTC + .. note:: To get all string possibilities, check https://docs.python.org/3/library/time.html#time.strftime Getting Kubernetes resource names diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index a1c834403a6..284438d1dd8 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -95,14 +95,18 @@ def to_datetime(string, format="%Y-%m-%d %H:%M:%S"): return datetime.datetime.strptime(string, format) -def strftime(string_format, second=None): +def strftime(string_format, second=None, utc=False): ''' return a date string using string. See https://docs.python.org/3/library/time.html#time.strftime for format ''' + if utc: + timefn = time.gmtime + else: + timefn = time.localtime if second is not None: try: second = float(second) except Exception: raise AnsibleFilterError('Invalid value for epoch value (%s)' % second) - return time.strftime(string_format, time.localtime(second)) + return time.strftime(string_format, timefn(second)) def quote(a):