-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
57 lines (38 loc) · 1.44 KB
/
utils.py
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
import time
import ujson
from datetime import datetime
from pytz import timezone, UTC
ONE_HOUR_SECONDS = 60 * 60
ONE_WEEK_SECONDS = ONE_HOUR_SECONDS * 24 * 7
def beautiful_date(date, tehran=True):
if tehran:
date = date.replace(tzinfo=timezone('Asia/Tehran'))
tz = 'Tehran'
else:
date = date.replace(tzinfo=UTC)
tz = 'UTC'
return date.strftime('%a %b %d %Y %H:%M:%S ' + tz)
def beautiful_now(tehran=True):
return beautiful_date(datetime.today(), tehran=tehran)
def load_json(path, data_if_empty):
if not path.is_file():
save_json(path, data_if_empty)
return data_if_empty
with open(path, 'r') as data_file:
return ujson.load(data_file)
def save_json(path, data):
with open(path, 'w') as data_file:
ujson.dump(data, data_file)
def human_format(num, precision=1, suffixes=['', 'k', 'm', 'b']):
if abs(num) < 10000:
return f'{num}'
m = sum([abs(num / 1000.0 ** x) >= 1 for x in range(1, len(suffixes))])
return f'{num/1000.0**m:.{precision}f}{suffixes[m]}'
def lprint(msg, include_time=True, tehran=True):
time_prefix = f'{beautiful_now(tehran=tehran)}: ' if include_time else ''
print(f'{time_prefix}{msg}')
def sleep_until(sleep_time):
now = datetime.now()
until = datetime.fromtimestamp(int(now.timestamp()) + sleep_time)
lprint(f'sleeping for {sleep_time} seconds until {beautiful_date(until)}')
time.sleep(sleep_time)