Skip to content

Instantly share code, notes, and snippets.

@macndesign
Created May 13, 2022 22:05
Show Gist options
  • Save macndesign/e99662ecf6f40c462711fa0d92728187 to your computer and use it in GitHub Desktop.
Save macndesign/e99662ecf6f40c462711fa0d92728187 to your computer and use it in GitHub Desktop.
import re
import os
FOLDER = 'files'
def get_paths():
return [os.path.join(FOLDER, f) for f in os.listdir(FOLDER)]
def extract_datetime(filepath):
regex = r'(?P<date>\d{4}-\d{2}-\d{2})--(?P<time>\d{2}:\d{2})'
match = re.search(regex, filepath)
return [match.group('date'), match.group('time')]
def sum_hours(hours):
total_secs = 0
for tm in hours:
time_parts = [int(s) for s in tm.split(':')]
total_secs += (time_parts[0] * 60 + time_parts[1]) * 60
total_secs, _ = divmod(total_secs, 60)
hr, min = divmod(total_secs, 60)
return "%d:%02d" % (hr, min)
def sum_total_of_times_in_range(start_date, end_date):
# Start and end date in ISO format YYYY-MM-DD
paths = get_paths()
times = []
start_date_to_number = int(start_date.replace('-', ''))
end_date_to_number = int(end_date.replace('-', ''))
date_range = range(start_date_to_number, end_date_to_number + 1)
for path in paths:
date = extract_datetime(path)[0]
date_number = int(date.replace('-', ''))
if date_number in date_range:
time = extract_datetime(path)[1]
times.append(time)
return sum_hours(times)
start_date = input('Enter start date (YYY-MM-DD): ')
end_date = input('Enter end date (YYY-MM-DD): ')
print(sum_total_of_times_in_range(start_date, end_date))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment