-
Notifications
You must be signed in to change notification settings - Fork 0
/
mytime.py
444 lines (377 loc) · 11.3 KB
/
mytime.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# Script for summarizing time tracking information from daily notes.
from version import __version__
import os
import click
import dateutil
import logging
import pandas as pd
import pendulum
import re
import sys
from tabulate import tabulate
def extractTimeData(contents, prefix=""):
td = []
onsite = False
onsite_pattern = r"onsite:\s*true"
if re.search(onsite_pattern, contents):
onsite = True
pattern = r"Time\.(\w+)\.(.+):\s*(\d+\.?\d?)"
mobj = re.findall(pattern, contents)
for category, name, hours in mobj:
if prefix:
td.append([prefix, category, name, float(hours), onsite])
else:
td.append([category, name, float(hours), onsite])
return td
def getSummary(df, category):
areadf = df.loc[df["Category"] == category].drop(columns=["Category"])
areadf = areadf.groupby("Name")["Hours"].sum().reset_index()
areadf = areadf.sort_values(by=["Hours"], ascending=False)
total = areadf["Hours"].sum()
areadf["%"] = areadf["Hours"] / total * 100
return areadf, total
def getFilesInRange(fpath, begin, end):
begindate = dateutil.parser.parse(begin).date()
enddate = dateutil.parser.parse(end).date()
files = []
with os.scandir(fpath) as it:
for entry in it:
if entry.name.endswith(".md") and entry.is_file():
try:
filedate = dateutil.parser.parse(
os.path.basename(entry).split(".")[0]
).date()
if (begindate <= filedate) and (filedate <= enddate):
files.append(entry.path)
except dateutil.parser.ParserError:
continue
return files
def gettimedata(files):
timedata = []
for entry in files:
with open(entry, encoding="UTF-8") as f:
name = os.path.splitext(os.path.basename(entry))[0]
td = extractTimeData(f.read(), prefix=name)
if len(td) > 0:
timedata.extend(td)
df = pd.DataFrame(
timedata, columns=["Date", "Category", "Name", "Hours", "Onsite"]
).astype({"Hours": "float"})
return df
def getNumDays(df):
return df["Date"].nunique()
def printTable(table, tsv):
tblFmt = "github"
if tsv:
tblFmt = "tsv"
print(
tabulate(
table,
headers="keys",
showindex=False,
floatfmt=("", ".1f", ".2f"),
tablefmt=tblFmt,
)
)
def reportTimeSpent(path, categories, begin, end, tsv=False, onsite=False, brief=False):
files = []
if brief:
categories = ["Focus"]
else:
categories = normalizeCategories(categories)
try:
files = getFilesInRange(path, begin, end)
td = gettimedata(files)
for category in categories:
areas, total_hours = getSummary(td, category)
days = getNumDays(td)
if total_hours:
if not brief:
printTable(areas, tsv)
print()
print(f"Total hours: {total_hours: >6}")
print(f"Total days: {days: >6}")
print(f"Average hours/day: {total_hours/days: >6.1f}")
print()
if onsite:
onsite_days = getOnsiteDays(td)
print(
f"Total onsite days: {onsite_days: >6} ({(onsite_days/days*100):.0f}%)"
)
except ValueError as err:
print(f"Error parsing date: {err}")
return
def getOnsiteDays(df):
onsite = df.loc[df["Onsite"]]
return onsite["Date"].nunique()
def dumpTimeEntries(path, categories, begin, end):
categories = normalizeCategories(categories)
try:
files = getFilesInRange(path, begin, end)
td = gettimedata(files)
td = filterTimeData(td, categories)
td.to_csv(sys.stdout, index=False)
except ValueError as err:
print(f"Error parsing date: {err}")
return
def filterTimeData(df, categories):
return df[df["Category"].isin(categories)]
def normalizeCategories(categories):
# Normalize category strings
categories = [cat.title() for cat in categories]
if "All" in categories:
categories = ["Proj", "Area", "Focus", "Prof"]
return categories
##########################################################################
def get_dates_today():
today = pendulum.today().to_date_string()
return today, today
def get_dates_yesterday():
yesterday = pendulum.yesterday().to_date_string()
return yesterday, yesterday
def get_dates_thisweek():
today = pendulum.today()
start = today.start_of("week").to_date_string()
end = today.end_of("week").to_date_string()
return start, end
def get_dates_lastweek():
lastweek = pendulum.today().subtract(weeks=1)
start = lastweek.start_of("week").to_date_string()
end = lastweek.end_of("week").to_date_string()
return start, end
def get_dates_thismonth():
today = pendulum.today()
start = today.start_of("month").to_date_string()
end = today.end_of("month").to_date_string()
return start, end
def get_dates_lastmonth():
lastmonth = pendulum.today().subtract(months=1)
start = lastmonth.start_of("month").to_date_string()
end = lastmonth.end_of("month").to_date_string()
return start, end
def get_dates_thisquarter():
today = pendulum.today()
start = today.first_of("quarter").to_date_string()
end = today.last_of("quarter").to_date_string()
return start, end
def get_dates_lastquarter():
lastmonth = pendulum.today().subtract(months=3)
start = lastmonth.first_of("quarter").to_date_string()
end = lastmonth.last_of("quarter").to_date_string()
return start, end
def get_dates_thisyear():
today = pendulum.today()
start = today.start_of("year").to_date_string()
end = today.end_of("year").to_date_string()
return start, end
def get_dates_lastyear():
lastyear = pendulum.today().subtract(years=1)
start = lastyear.start_of("year").to_date_string()
end = lastyear.end_of("year").to_date_string()
return start, end
def get_dates(
start,
end,
today,
yesterday,
thisweek,
thismonth,
thisquarter,
thisyear,
lastweek,
lastmonth,
lastquarter,
lastyear,
):
start = start.strftime("%Y-%m-%d")
end = end.strftime("%Y-%m-%d")
if today:
start, end = get_dates_today()
elif yesterday:
start, end = get_dates_yesterday()
elif thisweek:
start, end = get_dates_thisweek()
elif thismonth:
start, end = get_dates_thismonth()
elif thisquarter:
start, end = get_dates_thisquarter()
elif thisyear:
start, end = get_dates_thisyear()
elif lastweek:
start, end = get_dates_lastweek()
elif lastmonth:
start, end = get_dates_lastmonth()
elif lastquarter:
start, end = get_dates_lastquarter()
elif lastyear:
start, end = get_dates_lastyear()
return start, end
##########################################################################
@click.command()
@click.version_option(version=__version__)
@click.option("--log", default="warning", help="Logging level (info, debug)")
@click.option(
"--path",
default=".",
help="Path where the files containing the time tracking data is stored.",
type=click.Path(exists=True, file_okay=False),
)
@click.option(
"--category",
default=["All"],
multiple=True,
help="Category of time entries to summarise",
type=click.Choice(["Area", "Focus", "Proj", "Prof", "All"], case_sensitive=False),
)
@click.option(
"--csv",
default=False,
is_flag=True,
help="Format the output as comma separated values with one row per time entry",
)
@click.option(
"--tsv",
default=False,
is_flag=True,
help="Format the output as tab separated values",
)
@click.option(
"--from",
"from_",
default=pendulum.today(),
help="Start of time tracking period (default is today).",
type=click.DateTime(),
)
@click.option(
"--to",
default=pendulum.today(),
help="End of time tracking period (default is today).",
type=click.DateTime(),
)
@click.option(
"--today",
default=False,
is_flag=True,
help="Today's time summary. Overrides --from and --to values.",
)
@click.option(
"--yesterday",
default=False,
is_flag=True,
help="Yesterday's time summary. Overrides --from and --to values.",
)
@click.option(
"--thisweek",
default=False,
is_flag=True,
help="This week's time summary. Overrides --from and --to values.",
)
@click.option(
"--thismonth",
default=False,
is_flag=True,
help="This month's time summary. Overrides --from and --to values.",
)
@click.option(
"--thisquarter",
default=False,
is_flag=True,
help="This quarter's time summary. Overrides --from and --to values.",
)
@click.option(
"--thisyear",
default=False,
is_flag=True,
help="This year's time summary. Overrides --from and --to values.",
)
@click.option(
"--lastweek",
default=False,
is_flag=True,
help="Last week's time summary. Overrides --from and --to values.",
)
@click.option(
"--lastmonth",
default=False,
is_flag=True,
help="Last month's time summary. Overrides --from and --to values.",
)
@click.option(
"--lastquarter",
default=False,
is_flag=True,
help="Last quarter's time summary. Overrides --from and --to values.",
)
@click.option(
"--lastyear",
default=False,
is_flag=True,
help="Last year's time summary. Overrides --from and --to values.",
)
@click.option(
"--onsite",
default=False,
is_flag=True,
help="Include onsite information in the summary.",
)
@click.option(
"--brief", default=False, is_flag=True, help="Brief summary of time entries."
)
def mytime(
log,
path,
category,
csv,
tsv,
from_,
to,
today,
yesterday,
thisweek,
thismonth,
thisquarter,
thisyear,
lastweek,
lastmonth,
lastquarter,
lastyear,
onsite,
brief,
):
"""Summarize time tracking data.
Multiple options are provided for specifying the time period. Only the time
tracking data within the specified time period will be analysed. If no time
period is specified, today's time tracking info will be analyzed.
Time tracking information is extracted from 'Daily Note' files which follow
the convention that there is a separate file for each day and the file name
follows the pattern: 'YYYY-MM-DD.md', e.g. 2023-10-31.md.
"""
# Logging setup
numeric_level = getattr(logging, log.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f"Invalid log level: {log}")
logging.basicConfig(format="%(message)s", level=numeric_level)
# Tune pandas settings
pd.set_option("display.precision", 2)
start, end = get_dates(
from_,
to,
today,
yesterday,
thisweek,
thismonth,
thisquarter,
thisyear,
lastweek,
lastmonth,
lastquarter,
lastyear,
)
logging.info(f"{start} -> {end}")
if csv:
dumpTimeEntries(path, category, start, end)
else:
reportTimeSpent(path, category, start, end, tsv, onsite, brief)
##########################################################################
if __name__ == "__main__":
mytime()