rc/bin/work

297 lines
9.5 KiB
Text
Raw Permalink Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
2020-06-19 03:28:23 +00:00
import notify
from signal import signal, SIGINT
import sys
from time import sleep
from os.path import expanduser, join
from datetime import datetime, timedelta
TIME_FILE = join(expanduser("~"), "timekeeping.csv")
TODAY_FILE = join(expanduser("~"), ".timekeeping")
is_on_break = False
today_fields = []
start_time = datetime.now()
def die(*args):
print("Error: {}".format(*args), file=sys.stderr)
sys.exit(1)
def log(*args):
print(*args, file=sys.stderr)
def signal_handler(signal, frame):
global today_fields
now = datetime.now()
hour = now.strftime("%H:%M")
if not is_on_break:
sys.exit(0)
else:
break_time = now - start_time
log("\nBreak ended at {} and lasted {}".format(
hour, td_format(break_time)))
today_fields.append(start_time.strftime("%H:%M"))
today_fields.append(hour)
with open(TODAY_FILE, "w") as f:
f.write(",".join(today_fields))
sys.exit(0)
def td_format(td):
2020-04-17 18:24:40 +00:00
prefix = ""
if td < timedelta(0):
td = -td
prefix = "-"
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
2020-04-17 18:24:40 +00:00
return '{}{:d}:{:02d}'.format(prefix, int(hours), int(minutes))
def get_today_fields():
try:
with open(TODAY_FILE, "r") as f:
2020-02-28 22:37:00 +00:00
line_count = 0
for line in f:
2020-02-28 22:37:00 +00:00
line_count += 1
if line_count > 1:
log("Warning: incomplete day leftover in {}".format(TODAY_FILE))
if line.startswith(start_time.strftime("%Y-%m-%d")):
return line.strip().split(",")
except FileNotFoundError:
return []
return []
def work(args):
2020-02-19 22:59:28 +00:00
total_delta = timedelta()
month_delta = timedelta()
count = 0
month_count = 0
with open(TIME_FILE, "r") as f:
for line in f:
fields = line.strip().split(",", 5)
date = datetime.strptime(fields[0], "%Y-%m-%d")
t = datetime.strptime(fields[4], "%H:%M")
delta = timedelta(hours=t.hour, minutes=t.minute)
if date.month == start_time.month:
month_delta += delta
month_count += 1
total_delta += delta
count += 1
eight_h = timedelta(hours=8) * count
2020-03-02 22:07:08 +00:00
mean_time = total_delta / count if count > 0 else total_delta
2020-02-19 22:59:28 +00:00
minutes = total_delta - eight_h
2020-03-02 22:07:08 +00:00
month_mean_time = month_delta / month_count if month_count > 0 else month_delta
2020-02-19 22:59:28 +00:00
month_min = month_delta - timedelta(hours=(8 * month_count))
print("stats: {}, {}".format(
td_format(mean_time),
td_format(minutes)))
print("month stats: {}, {}".format(
td_format(month_mean_time),
td_format(month_min)))
# Try to calculate remaining time
fields = get_today_fields()
2020-02-19 22:59:28 +00:00
hour = start_time.strftime("%H:%M")
if not fields:
print("No work ongoing")
return
fields.append(hour)
# Test for even number of timestamp (but fields[0] is the date)
if len(fields) < 3:
die("not enough fields in {}".format(TODAY_FILE))
elif len(fields) % 2 == 0:
# Break in progress
log("Break in progress")
return
begin_time = None
worked_time = timedelta()
for field in fields[1:]:
try:
if begin_time is None:
begin_time = datetime.strptime(field, "%H:%M")
else:
end_time = datetime.strptime(field, "%H:%M")
worked_time += end_time - begin_time
begin_time = None
except ValueError:
die("couldn't parse field '{}' in {}".format(
field, TODAY_FILE))
day_start = datetime.strptime(fields[1], "%H:%M")
day_end = datetime.strptime(fields[-1], "%H:%M")
total_time = day_end - day_start
break_time = total_time - worked_time
day_end_estimation = day_start + timedelta(hours=8) + break_time
print("Worked {} already today. Estimated leave at {}".format(
td_format(worked_time),
day_end_estimation.strftime("%H:%M")))
def work_start(args):
fields = get_today_fields()
2020-04-15 14:22:14 +00:00
try:
hour = datetime.strptime(args.time, "%H:%M")
except ValueError:
die("Error: {} is not a valid time".format(args.time))
if fields:
die("You already started working")
2020-02-28 22:37:00 +00:00
with open(TODAY_FILE, "a") as f:
f.write("{},{}".format(
2020-04-15 14:22:14 +00:00
start_time.strftime("%Y-%m-%d"),
hour.strftime("%H:%M")))
log("Started working at {}".format(hour.strftime("%H:%M")))
def work_pause(args):
global is_on_break
global today_fields
is_on_break = True
today_fields = get_today_fields()
hour = start_time.strftime("%H:%M")
if not today_fields:
die("no work to take a break from")
log("Taking a break at {}".format(hour))
2020-06-19 03:28:23 +00:00
notify.init("work")
# Wait to be stopped by a Ctrl-C
2020-06-19 03:28:23 +00:00
reminder_interval = 5 # In minutes
count = 0
while True:
sleep(reminder_interval * 60)
count += 1
notify.send("Pause reminder",
"It has now been {} minutes".format(count * reminder_interval))
def work_end(args):
fields = get_today_fields()
hour = start_time.strftime("%H:%M")
if not fields:
die("Why try to leave when you haven't even started")
fields.append(hour)
if len(fields) < 3:
die("not enough fields in {}".format(TODAY_FILE))
# Test for even number of timestamp (but fields[0] is the date)
elif len(fields) % 2 == 0:
die("odd number of timestamps in {}".format(TODAY_FILE))
begin_time = None
worked_time = timedelta()
for field in fields[1:]:
try:
if begin_time is None:
begin_time = datetime.strptime(field, "%H:%M")
else:
end_time = datetime.strptime(field, "%H:%M")
worked_time += end_time - begin_time
begin_time = None
except ValueError:
die("couldn't parse field '{}' in {}".format(
field, TODAY_FILE))
day_start = datetime.strptime(fields[1], "%H:%M")
day_end = datetime.strptime(fields[-1], "%H:%M")
total_time = day_end - day_start
break_time = total_time - worked_time
with open(TIME_FILE, "a") as f:
2020-06-19 01:42:35 +00:00
f.write('{},{},{},{},{},"{}"\n'.format(
fields[0],
day_start.strftime("%H:%M"),
start_time.strftime("%H:%M"),
td_format(break_time),
td_format(worked_time),
args.description))
# Erase TODAY_FILE
with open(TODAY_FILE, "w") as f:
f.write("")
f.flush()
log("Finished working at {} after working {}".format(
hour, td_format(worked_time)))
def work_export(args):
print("export")
def work_parse(args):
2020-02-19 17:12:28 +00:00
new_lines = []
try:
with open(args.file, "r") as f:
for line in f:
2020-11-11 03:56:52 +00:00
fields = line.strip().split(",")
2020-02-19 17:12:28 +00:00
if len(fields) < 6:
2020-02-28 22:37:00 +00:00
log("Record: '{}' hasn't got enough fields ({})".format(line, len(fields)))
continue
times = []
for field in fields[1:]:
try:
time = datetime.strptime(field, "%H:%M")
times.append(time)
except ValueError:
break
if len(times) % 2 != 0:
die("Error: uneven number of timestamps ({}) in line '{}'".format(len(times), line))
desc = ','.join(fields[len(times)+1:]).strip()
worked_time = timedelta()
for i in range(int(len(times) / 2)):
worked_time += times[i * 2 + 1] - times[i * 2]
morning = times[0]
evening = times[-1]
2020-02-19 17:12:28 +00:00
full_day = evening - morning
break_time = full_day - worked_time
2020-02-19 17:12:28 +00:00
new_lines.append('{},{},{},{},{},{}'.format(
fields[0],
morning.strftime("%H:%M"),
evening.strftime("%H:%M"),
td_format(break_time),
td_format(worked_time),
desc))
2020-02-19 17:12:28 +00:00
except FileNotFoundError:
die("file not found: {}".format(args.file))
# TODO do sanity checking, like if a day already exists
with open(TIME_FILE, "a") as f:
for line in new_lines:
f.write("{}\n".format(line))
log("Written {} new entries to {}".format(len(new_lines), TIME_FILE))
if __name__ == "__main__":
# Handle Ctrl-C
signal(SIGINT, signal_handler)
parser = argparse.ArgumentParser()
parser.set_defaults(func=work)
commands = parser.add_subparsers(dest="command")
start_parser = commands.add_parser("start")
pause_parser = commands.add_parser("pause")
end_parser = commands.add_parser("end")
export_parser = commands.add_parser("export")
parse_parser = commands.add_parser("parse")
start_parser.set_defaults(func=work_start)
2020-04-15 14:22:14 +00:00
start_parser.add_argument("time", nargs="?", default=datetime.now().strftime("%H:%M"))
pause_parser.set_defaults(func=work_pause)
end_parser.set_defaults(func=work_end)
2020-04-15 14:22:14 +00:00
end_parser.add_argument("description")
export_parser.set_defaults(func=work_export)
parse_parser.set_defaults(func=work_parse)
2020-02-19 17:12:28 +00:00
parse_parser.add_argument("file")
args = parser.parse_args()
args.func(args)
#now = datetime.now()
#with open(TIME_FILE, "r") as f:
# for line in f:
# print(line.strip())