nxy/bot/utils.py

67 lines
1.5 KiB
Python
Raw Normal View History

2017-07-07 00:11:20 +00:00
# -*- coding: utf-8 -*-
import re
import random
2017-07-31 13:29:59 +00:00
from typing import Tuple
2017-07-07 00:11:20 +00:00
from pprint import pprint
from datetime import datetime, timedelta
TIME_UNITS = {
's': 'seconds',
'm': 'minutes',
'h': 'hours',
'd': 'days',
'w': 'weeks',
'mon': 'months',
'y': 'years',
}
pp = pprint
def date_from_iso(date: str) -> datetime:
return datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
def time_delta(text: str) -> timedelta:
2017-08-16 12:39:44 +00:00
match = re.match(r'(\d+)(s|m|h|d|mon|w|y)', text)
2017-07-07 00:11:20 +00:00
if match:
num, unit = match.groups()
num = int(num)
2017-08-16 12:39:44 +00:00
if unit == 's':
unit = 'seconds'
elif unit == 'm':
unit = 'minutes'
elif unit == 'h':
unit = 'hours'
elif unit == 'd':
unit = 'days'
elif unit == 'w':
unit = 'weeks'
elif unit == 'mon':
unit = 'weeks'
2017-07-07 00:11:20 +00:00
num *= 4
elif unit == 'y':
2017-08-16 12:39:44 +00:00
unit = 'weeks'
2017-07-07 00:11:20 +00:00
num *= 52
return timedelta(**{unit: num})
2017-07-31 13:29:59 +00:00
def parse_int(val: str, select: bool = True) -> Tuple[int, str]:
2017-07-07 00:11:20 +00:00
try:
val = int(val)
if val is not 0:
if val < 1:
order = 'desc'
val *= -1
else:
order = 'asc'
if select:
val -= 1
return val, order
except ValueError:
pass
def re_generator(low: int = 5, high: int = 20) -> str:
2017-08-16 12:39:44 +00:00
return 'R{}'.format('E' * random.randint(low, high))