#!/usr/bin/env python3 from datetime import date, datetime, timedelta import argparse import os def get_current_date(): return date.today().strftime("%Y-%m-%d") def get_timefile_line(date, time, desc): return date + " " + time + " " + desc + "\n" def get_total(filename): with open(filename, 'r') as time_file: total_time = timedelta() for line in time_file: date_time_description = line.split(" ", 2) hours, minutes = date_time_description[1].split(':', 1) # Parse the time to integers hours_int = int(hours) minutes_int = int(minutes) # Make sure that both the hours and the minutes are negative if there's a "-" before the time if hours_int < 0: minutes_int *= -1 delta = timedelta(hours=hours_int, minutes=minutes_int) total_time += delta return total_time # Parse command line arguments parser = argparse.ArgumentParser(prog='time.txt', description="Description") subparsers = parser.add_subparsers(help='sub-command help', dest='mode') parser.add_argument("-f", "--file") # create the parser for the "a" command parser_a = subparsers.add_parser('total', help='a help') # create the parser for the "b" command parser_b = subparsers.add_parser('add', help='b help') parser_b.add_argument("date", nargs='?', default=get_current_date()) parser_b.add_argument("time") parser_b.add_argument("description") parser_b = subparsers.add_parser('bill', help='b help') parser_b.add_argument("date", nargs='?', default=get_current_date()) parser_b.add_argument("time") parser_b.add_argument("description") parser_c = subparsers.add_parser('create', help='b help') args = parser.parse_args() filename = args.file if args.file else 'time.txt' if not args.mode or args.mode == "total": print("Total time:", get_total(filename)) elif args.mode == "add": with open(filename, 'a') as time_file: # TODO: Validate date and time time_file.write(get_timefile_line(args.date, args.time, args.description)) print("New total:", get_total(filename)) elif args.mode == "bill": with open(filename, 'a') as time_file: # TODO: Validate date and time time_file.write(get_timefile_line(args.date, "-" + args.time, args.description)) print("New total:", get_total(filename)) elif args.mode == "create": if (os.path.exists(filename)): print("Error: File", filename, "already exists, can't create a new one!") else: with open(filename, 'w') as time_file: time_file.write(get_timefile_line(get_current_date(), "00:01", "Setup time.txt"))