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j '  'P$a ( `D$Na L?u80e J,K˷NI'0eݷ(NI'؀ 2ipIIKp`:O'`ʤxB8Ѥx Ѥx $ $P6 :vRNb 'p,>NB 'P]-->P T+*^h& p '‰a ‰ (ĵt#u33;Nt̵'ޯ; [3W ~]0KH1q@8]O2]3*̧7# *p>us p _6]/}-4|t'|Smx= DoʾM×M_8!)6lq':l7!|4} '\ne t!=hnLn (~Dn\+‰_4k)0e@OhZ`F `.m1} 'vp{F`ON7Srx 'D˸nV`><;yMx!IS钦OM)Ե٥x 'DSD6bS8!" ODz#R >S8!7ّxEh0m$MIPHi$IvS8IN$I p$O8I,sk&I)$IN$Hi$I^Ah.p$MIN$IR8I·N "IF9Ah0m$MIN$IR8IN$I 3jIU;kO$ɳN$+ q.x* tEXtComment

Viewing File: /opt/cloudlinux/venv/lib/python3.11/site-packages/lvestats/lib/commons/dateutil.py

# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

import calendar
import datetime as datetimelib
from datetime import datetime, timedelta, timezone
import time
import re
from typing import Tuple


PARSE_PERIOD_PATTERN = re.compile(r'(\d+)(d|h|m|s)')
MAX_PERIOD_FOR_PARSING = 315360000  # 10 years


class _UTC(datetimelib.tzinfo):
    """UTC"""

    def utcoffset(self, dt):
        return datetimelib.timedelta(0)

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return datetimelib.timedelta(0)


UTC = _UTC()


def gm_to_local(date_time):
    """
    Converts date_time from UTC to local time
    :param date_time:
    :return:
    """
    return datetime.fromtimestamp(calendar.timegm(date_time.timetuple()))


def local_to_gm(date_time):
    """
    Converts date_time from local to UTC
    :param date_time:
    :return:
    """
    return datetime.fromtimestamp(time.mktime(date_time.timetuple()), tz=timezone.utc)


def gm_datetime_to_unixtimestamp(dt=datetime.utcnow()):
    """
    Converts utc datetime to timestamp
    :param dt:
    :return:
    """
    return calendar.timegm(dt.timetuple())


def unixtimestamp_to_gm_datetime(ts):
    """
    Converts timestamp to utc datetime
    :param ts:
    :return:
    """
    return datetime.fromtimestamp(ts, tz=UTC)


def str_to_timedelta(period_str):
    time_num = int(period_str[:-1])
    time_type = period_str[-1]
    if time_type == 'm':
        return timedelta(minutes=time_num)
    if time_type == 'h':
        return timedelta(hours=time_num)
    if time_type == 'd':
        return timedelta(days=time_num)
    raise ValueError(
        f'Error: period "{period_str}" is incorrect. Please, specify '
        'minutes with m, hours with h, days with d'
    )


def round_1m(dt):
    return dt.replace(second=0, microsecond=0)


def parse_period(period_str, now=None):
    """
    Parses string period (in local time),
    example values such are 'today', 'yesterday', '5m', '4h', etc
    :param period_str:str:
    :param now:
    :return:
    """
    now = now or datetime.now()
    val = period_str.lower()
    if val == 'today':
        return round_1m(now.replace(hour=0, minute=0)), now

    elif val == 'yesterday':
        today = round_1m(now.replace(hour=0, minute=0))
        return today - timedelta(days=1), today
    else:
        return now - str_to_timedelta(period_str), now


def ts_to_iso(ts):
    return gm_to_local(unixtimestamp_to_gm_datetime(ts)).isoformat()


def parse_date(date_str):
    """
    Parses date time string specified into a naive date time object (timezone unaware),
    that is expected to be in local time.

    :param date_str:
    :return:
    """
    last_ex = []
    for f in ('%Y-%m-%d', '%Y-%m-%d %H:%M', '%y-%m-%d %H:%M', '%y-%m-%d'):
        try:
            return datetime.strptime(date_str, f)
        except ValueError as ex:
            last_ex.append(ex)

    raise ValueError("please use [YY]YY-MM-DD[ HH:MM] format", *last_ex)


def convert_to_seconds(td):
    """
    Convert timedelta <type 'datetime.timedelta'> to seconds <type 'int'>
    :param datetime.timedelta td: timedelta
    :return int: seconds
    """
    try:
        return td.total_seconds()
    except AttributeError:
        return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) // 10**6


time_units = {
    'd': 60 * 60 * 24,
    'h': 60 * 60,
    'm': 60,
    's': 1,
}

units_of_time = {
    'seconds': 's',
    'minutes': 'm',
    'hours': 'h',
    'days': 'd',
}


def parse_period2(period):
    """
    Return in seconds time period
    support that format [D[D..]d][H[H..]h][M[M..]m][S[S..]][s] format; D[D..]d - D[D..] days, H[H..]h - H[H..] hours,
    M[M..]m - M[M..] minutes, S[S..]s - S[S..] seconds
    :param str period: period line
    :return int: seconds
    :raises: ValueError
    """
    msg_ = (
        f'{period} is incorrect; use today, yesterday or [D[D..]d][H[H..]h][M[M..]m][S[S..]][s] format; '
        'D[D..]d - D[D..] days, H[H..]h - H[H..] hours, M[M..]m - M[M..] minutes, S[S..]s - S[S..] seconds'
    )
    time_seconds = int(0)
    length_of_matched_strings = 0
    for dig, unit in PARSE_PERIOD_PATTERN.findall(period):
        length_of_matched_strings += len(dig) + 1
        time_seconds += int(dig) * time_units[unit]
        if time_seconds > MAX_PERIOD_FOR_PARSING:
            raise ValueError(f'{period} is incorrect; period can not be more than 3600 days')
    if not time_seconds or length_of_matched_strings < len(period):
        raise ValueError(msg_)
    return time_seconds


def time_dict_to_seconds(time_dict):
    """
    FIXME: we could avoid such extra conversions of units across various our
    projects if we just use seconds everywhere and convert to other larger
    units only before show them to end-user. Currently we parse/reconstruct
    this ~3 times before we use in statsnotifier.py end-code.
    :param time_dict: like {'period': 5, 'unitOfTime': 'seconds'}
    :return: str '5s'
    """
    return parse_period2(f'{time_dict["period"]}{units_of_time[time_dict["unitOfTime"]]}')


conversion_table = [
    ('days',     60 * 60 * 24),
    ('hours',    60 * 60),
    ('minutes',  60),
    ('seconds',  1),
]


def seconds_to_human_view(seconds) -> Tuple[int, str]:
    """
    Convert provided second number to human view:
     60 -> 1, 'minutes'
     59 -> 59 , 'seconds'
     3601 -> 1, 'hours'
    :param seconds: Seconds number
    :return: Tuple (number, english_name)
    """
    for human_str, unit in conversion_table:
        if seconds // unit > 0:
            return seconds // unit, human_str
Back to Directory=ceiIENDB`