comparison scripts/getan-daily-report @ 490:11d97a40dfa5

Renamed getan-day-report to getan-daily-report. Cosmetics
author Magnus Schieder <mschieder@intevation.de>
date Thu, 05 Jul 2018 15:05:40 +0200
parents scripts/getan-day-report@d80f40d239d2
children a4044956e08c
comparison
equal deleted inserted replaced
489:fbb6f829c643 490:11d97a40dfa5
1 #!/usr/bin/env python3
2 """
3 write a daily report accessing a database from
4 http://hg.intevation.de/getan 1.1dev3.
5 """
6 # hastily done, written to learn the getan database format and its manipulation
7 # Free Software under GNU GPL v>=3
8 # 20130109 bernhard@intevation.de
9 # 20140103 bernhard@intevation.de:
10 # started from 2013/getan-writeout-timesorted.py
11 # ported to python3. Removed the dependency for functions from worklog.py.
12 # the timesorted variant can be uncommented in the code for now
13 # 20140109 bernhard@intevation.de:
14 # Total time output format improved.
15 # 20140120 bernhard@intevation.de:
16 # added command line options, requires argparse module now (e.g. Python>=3.2)
17 # 20141104 bernhard@intevation.de:
18 # migration to argparse complete, added -t option
19 # TODO:
20 # * use python v>=3.2 variants in the code where noted.
21
22 import argparse
23 import datetime
24 import logging
25 import sqlite3
26
27 factor = {'privat': 0}
28
29 l = logging
30 l.basicConfig(level=logging.INFO,
31 # l.basicConfig(level=logging.DEBUG,
32 format='%(message)s')
33 # format='%(asctime)s %(levelname)s %(message)s')
34
35
36 def hhhmm_from_timedelta(td):
37 """Return a string '-HHH:MM' from the timedelta parameter.
38
39 Accounts for way the integer division works for negative numbers:
40 -2 // 60 == -1
41 -2 % 60 == 58
42 by first working on the positive number and then adding the minus
43 to the string.
44
45 For python >=3.1. Successor of hhmm_from_timedelta() from
46 http://intevation.de/cgi-bin/viewcvs-misc.cgi/worklog.py/ .
47 """
48 total_minutes = abs(round(td.days * 24 * 60 + td.seconds / 60))
49 # variant for Python v>3.2:
50 # total_minutes = abs(round(td/datetime.timedelta(minutes=1)))
51
52 hours = total_minutes // 60
53 minutes = total_minutes % 60
54
55 h_string = "{}".format(hours)
56
57 if(td.days < 0):
58 h_string = "-" + h_string
59
60 return "{:>3s}:{:02d}".format(h_string, minutes)
61
62
63 def self_test():
64 """Run some simple tests on hhhmm_from_timedelta().
65
66 e.g. run like
67 python3 -c 'from getan_report_20140103 import *; self_test()'
68 """
69 l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=1)))
70 l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=-2)))
71
72
73 def main():
74 parser = argparse.ArgumentParser(description=__doc__)
75 parser.add_argument("-t", action='store_true',
76 help="timesorted output and default reportday to today")
77 parser.add_argument("dbfilename")
78 parser.add_argument("reportday", nargs='?',
79 help="day to report yyyy-mm-dd")
80
81 args = parser.parse_args()
82 l.debug(args)
83
84 if args.reportday:
85 try:
86 report_range_start = \
87 datetime.datetime.strptime(args.reportday, "%Y-%m-%d")
88 except ValueError:
89 report_range_start = \
90 datetime.datetime.strptime(args.reportday, "%Y%m%d")
91
92 elif args.t:
93 # start with today 00:00
94 report_range_start = datetime.datetime.combine(
95 datetime.date.today(), datetime.time())
96 else:
97 # start with yesterday 00:00
98 report_range_start = datetime.datetime.combine(
99 datetime.date.today() - datetime.timedelta(days=1),
100 datetime.time())
101 report_range_end = report_range_start + datetime.timedelta(days=1)
102
103 l.info("Opening sqlite3 database '%s'" % args.dbfilename)
104 conn = sqlite3.connect(
105 args.dbfilename,
106 detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
107 c = conn.cursor()
108
109 tasks = {}
110 task_total = {}
111
112 c.execute('select * from projects')
113 for t in c:
114 l.debug(t)
115 tasks[t[0]] = t[2]
116 task_total[t[0]] = datetime.timedelta()
117
118 # from getan 1.0 20130103
119 # CREATE TABLE entries (
120 # id INTEGER PRIMARY KEY AUTOINCREMENT,
121 # project_id INTEGER REFERENCES projects(id),
122 # start_time TIMESTAMP NOT NULL,
123 # stop_time TIMESTAMP NOT NULL,
124 # description VARCHAR(256),
125 #
126 # CHECK (strftime('%s', start_time) <= strftime('%s', stop_time))
127 # );
128
129 total_time = datetime.timedelta()
130
131 if args.t:
132 c.execute('select * from entries order by start_time')
133 else:
134 c.execute('select * from entries order by project_id')
135 for e in c:
136 l.debug(e)
137 # let us ignore microseconds
138 start_time = e[2].replace(microsecond = 0)
139 stop_time = e[3].replace(microsecond = 0)
140 length = stop_time - start_time
141
142 desc = tasks[e[1]]
143
144 if start_time >= report_range_start and start_time < report_range_end:
145 if args.t:
146 print("{0:%Y-%m-%d %H:%M}-\n"
147 "{1:%Y-%m-%d %H:%M} {4} {2}: {3}\n".
148 format(start_time, stop_time, desc, e[4],
149 hhhmm_from_timedelta(length)))
150 else:
151 print("{0} {2}: {3} {4}".
152 format(start_time, stop_time, desc, e[4],
153 hhhmm_from_timedelta(length)))
154 if desc in factor:
155 # python3.1 does not allow timedelta division.
156 # TODO: Make python3.1 save or update to python3.2.
157 # l.info("applying factor %f to entry %s" % (factor[desc], e))
158 # length = (length * int(factor[desc]*1000))/1000
159 # Until python3.2 we only honor a factor of zero:
160 if factor[desc] == 0:
161 length = datetime.timedelta(0)
162 l.info("not counting {}".format(e))
163 else:
164 l.info("ignoring factor {}".factor[desc])
165 total_time += length
166 task_total[e[1]] += length
167
168 print("(" + hhhmm_from_timedelta(total_time).strip() + ")")
169 for t in tasks:
170 if task_total[t] != datetime.timedelta(0):
171 print("\t" + tasks[t], hhhmm_from_timedelta(task_total[t]))
172
173 c.close()
174
175 if __name__ == "__main__":
176 main()
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)