# 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