File: date_utils.py

package info (click to toggle)
python-influxdb-client 1.40.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,216 kB
  • sloc: python: 60,236; sh: 64; makefile: 53
file content (96 lines) | stat: -rw-r--r-- 2,946 bytes parent folder | download
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Utils to get right Date parsing function."""
import datetime
import threading
from datetime import timezone as tz

from dateutil import parser

date_helper = None

lock_ = threading.Lock()


class DateHelper:
    """
    DateHelper to groups different implementations of date operations.

    If you would like to serialize the query results to custom timezone, you can use following code:

    .. code-block:: python

        from influxdb_client.client.util import date_utils
        from influxdb_client.client.util.date_utils import DateHelper
        import dateutil.parser
        from dateutil import tz

        def parse_date(date_string: str):
            return dateutil.parser.parse(date_string).astimezone(tz.gettz('ETC/GMT+2'))

        date_utils.date_helper = DateHelper()
        date_utils.date_helper.parse_date = parse_date
    """

    def __init__(self, timezone: datetime.tzinfo = tz.utc) -> None:
        """
        Initialize defaults.

        :param timezone: Default timezone used for serialization "datetime" without "tzinfo".
                         Default value is "UTC".
        """
        self.timezone = timezone

    def parse_date(self, date_string: str):
        """
        Parse string into Date or Timestamp.

        :return: Returns a :class:`datetime.datetime` object or compliant implementation
                 like :class:`class 'pandas._libs.tslibs.timestamps.Timestamp`
        """
        pass

    def to_nanoseconds(self, delta):
        """
        Get number of nanoseconds in timedelta.

        Solution comes from v1 client. Thx.
        https://github.com/influxdata/influxdb-python/pull/811
        """
        nanoseconds_in_days = delta.days * 86400 * 10 ** 9
        nanoseconds_in_seconds = delta.seconds * 10 ** 9
        nanoseconds_in_micros = delta.microseconds * 10 ** 3

        return nanoseconds_in_days + nanoseconds_in_seconds + nanoseconds_in_micros

    def to_utc(self, value: datetime):
        """
        Convert datetime to UTC timezone.

        :param value: datetime
        :return: datetime in UTC
        """
        if not value.tzinfo:
            return self.to_utc(value.replace(tzinfo=self.timezone))
        else:
            return value.astimezone(tz.utc)


def get_date_helper() -> DateHelper:
    """
    Return DateHelper with proper implementation.

    If there is a 'ciso8601' than use 'ciso8601.parse_datetime' else use 'dateutil.parse'.
    """
    global date_helper
    if date_helper is None:
        with lock_:
            # avoid duplicate initialization
            if date_helper is None:
                _date_helper = DateHelper()
                try:
                    import ciso8601
                    _date_helper.parse_date = ciso8601.parse_datetime
                except ModuleNotFoundError:
                    _date_helper.parse_date = parser.parse
                date_helper = _date_helper

    return date_helper