Debian Codegraph @

cylc/flow/jinja/filters/duration_as.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) 2008-2019 NIWA
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Filter for formatting ISO8601 duration strings."""
17
18 from typing import Callable, Dict, Tuple
19
20 from metomi.isodatetime.parsers import DurationParser
21
22 SECONDS_PER_MINUTE = 60.0
23 MINUTES_PER_HOUR = 60.0
24 HOURS_PER_DAY = 24.0
25 DAYS_PER_WEEK = 7.0
26
27 SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR
28 SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY
29 SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK
30
31 CONVERSIONS: Dict[Tuple[str, str], Callable] = {
32 ('s', 'seconds'): float,
33 ('m', 'minutes'): lambda s: float(s) / SECONDS_PER_MINUTE,
34 ('h', 'hours'): lambda s: float(s) / SECONDS_PER_HOUR,
35 ('d', 'days'): lambda s: float(s) / SECONDS_PER_DAY,
36 ('w', 'weeks'): lambda s: float(s) / SECONDS_PER_WEEK,
37 }
38
39
40 def duration_as(iso8601_duration: str, units: str) -> float:
41 """Format an :term:`ISO8601 duration` string as the specified units.
42
43 Units for the conversion can be specified in a case-insensitive short or
44 long form:
45
46 - Seconds - "s" or "seconds"
47 - Minutes - "m" or "minutes"
48 - Hours - "h" or "hours"
49 - Days - "d" or "days"
50 - Weeks - "w" or "weeks"
51
52 While the filtered value is a floating-point number, it is often required
53 to supply an integer to workflow entities (e.g. environment variables) that
54 require it. This is accomplished by chaining filters:
55
56 - ``{{CYCLE_INTERVAL | duration_as('h') | int}}`` - 24
57 - ``{{CYCLE_SUBINTERVAL | duration_as('h') | int}}`` - 0
58 - ``{{CYCLE_INTERVAL | duration_as('s') | int}}`` - 86400
59 - ``{{CYCLE_SUBINTERVAL | duration_as('s') | int}}`` - 1800
60
61 Args:
62 iso8601_duration: Any valid ISO8601 duration as a string.
63 units: Destination unit for the duration conversion
64
65 Return:
66 The total number of the specified unit contained in the specified
67 duration as a floating-point number.
68
69 Raises:
70 ISO8601SyntaxError: In the event of an invalid datetime string.
71
72 Python Examples:
73 >>> # Basic usage.
74 >>> duration_as('PT1M', 's')
75 60.0
76 >>> duration_as('PT1H', 'seconds')
77 3600.0
78
79 >>> # Exceptions.
80 >>> duration_as('invalid value', 's') # doctest: +NORMALIZE_WHITESPACE
81 Traceback (most recent call last):
82 metomi.isodatetime.exceptions.ISO8601SyntaxError: Invalid ISO 8601\
83 duration representation: invalid value
84 >>> duration_as('invalid unit', '#') # doctest: +NORMALIZE_WHITESPACE
85 Traceback (most recent call last):
86 ValueError: No matching units found for #
87
88 Jinja2 Examples:
89 .. code-block:: cylc
90
91 {% set CYCLE_INTERVAL = 'PT1D' %}
92 {{ CYCLE_INTERVAL | duration_as('h') }} # 24.0
93 {% set CYCLE_SUBINTERVAL = 'PT30M' %}
94 {{ CYCLE_SUBINTERVAL | duration_as('hours') }} # 0.5
95 {% set CYCLE_INTERVAL = 'PT1D' %}
96 {{ CYCLE_INTERVAL | duration_as('s') }} # 86400.0
97 {% set CYCLE_SUBINTERVAL = 'PT30M' %}
98 {{ CYCLE_SUBINTERVAL | duration_as('seconds') }} # 1800.0
99
100 """
101 for converter_names in CONVERSIONS:
102 if units.lower() in converter_names:
103 converter = CONVERSIONS[converter_names]
104 break
105 else:
106 raise ValueError('No matching units found for %s' % units)
107 return converter(DurationParser().parse(iso8601_duration).get_seconds())