This is simple program to calculate working hours in given shift.. It is also return user sessions and presence of user shift.
while this works fine. I would like suggestion to improve it.
from datetime import datetime, timedelta
user_attendence = [{"id": 1, "punch": 1, "date": "22-04-2022 02:10:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 03:00:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 04:00:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 05:00:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 06:00:00"},
{"id": 1, "punch": 0, "date": "22-04-2022 08:00:10"},
{"id": 2, "punch": 1, "date": "22-04-2022 04:00:00"},
{"id": 2, "punch": 1, "date": "22-04-2022 05:00:00"},
]
time_format = '%H:%M:%S'
shift = ["22-04-2022 02:00:00", "22-04-2022 09:00:00"]
def getDays(obj):
return (datetime.strptime(obj[1], '%d-%m-%Y %H:%M:%S') - datetime.strptime(obj[0], '%d-%m-%Y %H:%M:%S')).days
def set_timeformat(self, formatstr=time_format):
self.time_format = formatstr
def converTime(obj):
return str(datetime.strptime(obj, '%d-%m-%Y %H:%M:%S').time())
def calculate(shift1, user_attendence, indate, id):
""""
timeList -> 02:00 AM, 08:00:AM
date -> 22-04-2022
"""
man_in = False
man_out = False
sessions = []
is_present = False
total_hours = datetime.strptime("00:00:00", '%H:%M:%S')
in_time = "null"
attendance = [i for i in user_attendence if shift1[0] <= i["date"] <= shift1[1] and i.get("id").__eq__(id)]
if [i for i in attendance if i.get("punch").__eq__(1)]:
is_present = True
if is_present:
for k in attendance:
if k["punch"].__eq__(1):
if not man_in:
in_time = converTime(k["date"])
man_in = True
man_out = False
else:
dif = datetime.strptime(converTime(k["date"]), time_format) - datetime.strptime(in_time, time_format)
in_time = converTime(k["date"])
total_hours += dif
man_out = False
sessions.append(convert(dif.seconds))
if k["punch"].__eq__(0):
if not man_out:
man_in = False
man_out = True
if in_time != "null":
dif1 = (datetime.strptime(converTime(k["date"]), time_format) - datetime.strptime(in_time, time_format))
total_hours += dif1
sessions.append(convert(dif1.seconds))
return is_present, total_hours.time().__str__(), sessions
else:
return is_present
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
t = calculate(shift, user_attendence, "22-04-2022", 1)
print(t)
output: (True, '05:00:10', ['1:00:00', '1:00:00', '1:00:00', '2:00:10'])
user_attendance
list actually come from? Is this a placeholder literal for what will eventually be some kind of user interface, or does the user interface exist already? Is it retrieved from a file? \$\endgroup\$