-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
88 lines (67 loc) · 2.5 KB
/
functions.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
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
import db_handler as db
import datetime
from pathlib import Path
from matplotlib import pyplot as plt
import os, os.path
from io import BytesIO
help_msg = '''
This bot helps you to track your weight
There are commands below:
/start - show this help page
/add_record - add new record
/add_skipped_record - add record for a past day
/del_record_1_day - delete last record that is not older than 1 day
/show_week - show weight dynamic for last 7 days
/show_month - show weight dynamic for last month
/show_n_days - show as many days as you want
/cancel - cancel any action
'''
def get_help_msg():
''' Just return help msg '''
return help_msg
def day_end_ts(t):
''' Return end of the day '''
dt = t.replace(second=59, microsecond=59, minute=59, hour=23)
ts = int(dt.timestamp())
return str(ts)
def get_target_day_ts(days):
''' Return ts of end of the day that was N days ago '''
today_end_ts = day_end_ts(datetime.datetime.now())
days_ts_delta = days * 24 * 60 * 60
target_date_ts = int(today_end_ts) - int(days_ts_delta)
return target_date_ts
def get_graph(user_id, days):
''' Get graph of weight dynamic for last N days '''
target_day_ts = get_target_day_ts(days)
filter = 'date_ts > ' + str(target_day_ts)
records = db.get_recs_by_filter(user_id, filter)
plt.figure()
title_tmplt = 'Weight dynamic: {date_from} - {date_to}'
title = title_tmplt.format(date_from=datetime.datetime.utcfromtimestamp(target_day_ts).strftime('%Y-%m-%d'),
date_to=datetime.datetime.today().strftime('%Y-%m-%d'))
plt.title(title)
plt.xlabel('Date')
plt.xticks(rotation=20)
plt.ylabel('Weight (kg)')
dates_arr = []
weights_arr = []
records.sort(key=lambda x: x.date_ts, reverse = False)
for rec in records:
dates_arr.append(datetime.datetime.utcfromtimestamp(rec.date_ts).strftime('%Y-%m-%d'))
weights_arr.append(rec.weight)
plt.plot(dates_arr, weights_arr)
plt.scatter(dates_arr, weights_arr)
plt.grid(ls=':')
buff = BytesIO()
plt.savefig(buff, format="png")
buff.seek(0)
return buff
def make_rec_readable(rec):
''' Make readable line with record info '''
line_template = 'id = {id}\n' \
'date UTC: {date}\n' \
'weight: {weight} {measure}\n' \
'comment: {comment}'
line = line_template.format(id=rec.id, date=datetime.datetime.utcfromtimestamp(rec.date_ts).strftime('%Y-%m-%d %H:%M:%S'),
weight=rec.weight, measure=rec.measure, comment=rec.comment )
return line