aboutsummaryrefslogtreecommitdiff
path: root/tools/run_tests/xds_k8s_test_driver/framework/helpers/datetime.py
blob: a4b2784916086b5c9be1be309a71fd0be7cc48da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Copyright 2021 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This contains common helpers for working with dates and time."""
import datetime
import re
from typing import Pattern

RE_ZERO_OFFSET: Pattern[str] = re.compile(r'[+\-]00:?00$')


def utc_now() -> datetime.datetime:
    """Construct a datetime from current time in UTC timezone."""
    return datetime.datetime.now(datetime.timezone.utc)


def shorten_utc_zone(utc_datetime_str: str) -> str:
    """Replace ±00:00 timezone designator with Z (zero offset AKA Zulu time)."""
    return RE_ZERO_OFFSET.sub('Z', utc_datetime_str)


def iso8601_utc_time(timedelta: datetime.timedelta = None) -> str:
    """Return datetime relative to current in ISO-8601 format, UTC tz."""
    time: datetime.datetime = utc_now()
    if timedelta:
        time += timedelta
    return shorten_utc_zone(time.isoformat())


def datetime_suffix(*, seconds: bool = False) -> str:
    """Return current UTC date, and time in a format useful for resource naming.

    Examples:
        - 20210626-1859   (seconds=False)
        - 20210626-185942 (seconds=True)
    Use in resources names incompatible with ISO 8601, e.g. some GCP resources
    that only allow lowercase alphanumeric chars and dashes.

    Hours and minutes are joined together for better readability, so time is
    visually distinct from dash-separated date.
    """
    return utc_now().strftime('%Y%m%d-%H%M' + ('%S' if seconds else ''))