calculate working hours for current week in django - python

let us consider start time, end time and Break time as
models.py
class Records(TimeStampedModel):
date = models.DateField()
start_time = models.TimeField(default='08:30')
end_time = models.TimeField(default='08:30')
break_time = models.FloatField(default=0.5, help_text="(Hrs)")
views.py
def record_working hours(request):
records = Records.objects.filter(created_by__client=request.user.client)
now = timezone.now()
today = timezone.now().date()
week_start = today - timedelta(days=(today.weekday()))
date_list = [week_start + timedelta(days=x) for x in range(5)]
week_last = date_list[-1]
working_time = records.filter(date__gte=week_start,date__lte=week_last)
for record in records:
work_hours = record.start_time - record.end_time - record.break_time
return redirect(reverse('record_list'))
Hear i need to calculate total working hours for current week but i am getting the error as " type object 'datetime.datetime' has no attribute 'datetime'" and when i print my start time, end time and break time i am getting as
start_time = datetime.time(8, 30)
end_time = datetime.time(18, 30)
break_time = 0.5
And also calculate total working hours for that week of all records

Related

Calculation of business working hour in python

I would like to write a function that calculate working business hours in python, to do that I don't like to define a class and use python ready function to calculate.
I tried with following code but the code is not working well. I need to modify the code and change it for the hour instead of minutes too.
Do you have any suggestion?
def getminutes(datetime1,datetime2,worktiming=[9, 17]):
day_hours = (worktiming[1]-worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
weekends=[6, 7]
# Set initial default variables
dt_start = datetime1.datetime # datetime of start
dt_end = datetime2.datetime # datetime of end
worktime_in_seconds = 0
if dt_start.date() == dt_end.date():
# starts and ends on same workday
full_days = 0
if dt_start in [6, 7]:
return 0
else:
if dt_start.hour < worktiming[0]:
# set start time to opening hour
dt_start = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour=worktiming[0],
minute=0)
if dt_start.hour >= worktiming[1] or \
dt_end.hour < worktiming[0]:
return 0
if dt_end.hour >= worktiming[1]:
dt_end = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[1],
minute=0)
worktime_in_seconds = (dt_end-dt_start).total_seconds()
elif (dt_end-dt_start).days < 0:
# ends before start
return 0
else:
# start and ends on different days
current_day = dt_start # marker for counting workdays
while not current_day.date() == dt_end.date():
if not is_weekend(current_day):
if current_day == dt_start:
# increment hours of first day
if current_day.hour < worktiming[0]:
# starts before the work day
worktime_in_seconds += day_minutes*60 # add 1 full work day
elif current_day.hour >= worktiming[1]:
pass # no time on first day
else:
# starts during the working day
dt_currentday_close = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour= worktiming[1],
minute=0)
worktime_in_seconds += (dt_currentday_close
- dt_start).total_seconds()
else:
# increment one full day
worktime_in_seconds += day_minutes*60
current_day += datetime.timedelta(days=1) # next day
# Time on the last day
if not is_weekend(dt_end):
if dt_end.hour >= worktiming[1]: # finish after close
# Add a full day
worktime_in_seconds += day_minutes*60
elif dt_end.hour < worktiming[0]: # close before opening
pass # no time added
else:
# Add time since opening
dt_end_open = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[0],
minute=0)
worktime_in_seconds += (dt_end-dt_end_open).total_seconds()
return int(worktime_in_seconds / 60)
How can I modify the code that works with the following input ?
getminutes(2019-12-02 09:30:00,2019-12-07 12:15:00,worktiming=[9, 17])
You can use pd.bdate_range(datetime1, datetime2) to compute the number of working days. When converting worktiming to a pandas datetime, it is easy to compute the difference (in seconds) between the two datetimes:
import pandas as pd
datetime1 = "2019-12-02 09:30:00"
datetime2 = "2019-12-07 12:15:00"
def getminutes(datetime1, datetime2, worktiming=[9, 17]):
d1 = pd.to_datetime(datetime1)
d2 = pd.to_datetime(datetime2)
wd = pd.bdate_range(d1, d2) # working days
day_hours = (worktiming[1] - worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
day_seconds = day_minutes * 60 # seconds in a work day
full_days = len(wd)
day1 = datetime1[:10]
day2 = datetime2[:10]
dt1 = pd.to_datetime(day1 + " " + str(worktiming[0]) + ":00")
dt2 = pd.to_datetime(day2 + " " + str(worktiming[1]) + ":00")
ex1, ex2 = 0, 0
if day1 in wd:
ex1 = max(pd.Timedelta(d1 - dt1).seconds, 0)
if day2 in wd:
ex2 = max(pd.Timedelta(dt2 - d2).seconds, 0)
total_seconds = full_days * day_seconds - ex1 - ex2
total_minutes = total_seconds / 60
total_hours = total_minutes / 60
return int(total_minutes)
print(getminutes(datetime1, datetime2))
Output: 2370

Subtract two datetime.time

i basicly need to get actual time(time1) and see how many hours and minutos to time2.
Its a countdown, how many time untill time2.
I have been making this
def schedule_task():
exp_h = 23
exp_m = 5
now = datetime.datetime.now()
if len(str(exp_m))==1:
exp_m=str("0")+str(exp_m)
date_time_str = str(exp_h)+":"+str(exp_m)+":00"
exp_now = datetime.datetime.strptime(date_time_str,"%H:%M:%S").time()
fdate = datetime.datetime.now().strftime("%H:%M:%S")
locl_h = now.strftime("%H")
locl_m = now.strftime("%M")
remain = datetime.datetime.combine(now.today(), fdate.time()) - datetime.datetime.combine(now.today(), exp_now)
lbl_remaing.config(text="Request will be sent in "+str(remain), bg="darkgrey",fg="blue")
if locl_h.strip()==exp_h.strip() and locl_m.strip()==exp_m.strip():
print("run func")
else:
lbl_remaing.after(1000, schedule_task)
Having this error
print("----> ",datetime.datetime.combine(now.today(), fdate.time())
datetime.datetime.combine(now.today(), exp_now.time())) AttributeError: 'str' object has no attribute 'time'
Got it:
start_time = datetime.time(int(exp_h), int(exp_m), 00)
stop_time = datetime.time(int(locl_h), int(locl_m), int(locl_s))
date = datetime.date(1, 1, 1)
datetime1 = datetime.datetime.combine(date, start_time)
datetime2 = datetime.datetime.combine(date, stop_time)
time_elapsed = datetime1 - datetime2

Python Timer Cooldown Example

I'm looking for a cooldown timer for python, basically just to print days,hours,minutes,seconds left from a certain date.
Thanks very much!
You can get the counter with the help of time delta function.
import datetime
import time
future_date = datetime.datetime.now()+ datetime.timedelta(seconds=3)
while True:
curr_date = datetime.datetime.now()
rem_time = future_date - curr_date
total_seconds = int(rem_time.total_seconds())
if total_seconds > 0:
days, h_remainder = divmod(total_seconds, 86400)
hours, remainder = divmod(h_remainder, 3600)
minutes, seconds = divmod(remainder, 60)
print("Time Left: {} days, {} hours, {} minutes, {} seconds".format(days, hours, minutes, seconds))
time.sleep(1)
else:
break
sample output will be:
Time Left: 0 days, 0 hours, 0 minutes, 2 seconds
Time Left: 0 days, 0 hours, 0 minutes, 1 seconds
Try this. The module datetime is preinstalled on Python, I believe.
import datetime
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
future = datetime.datetime(2022, 3, 31, 8, 0, 0)
difference = future - present
print(difference)
The format for datetime's future is: year, month, day, hour, minute, second.
Or, if you'd like to have user input:
import datetime
year = int(input('Enter the year of the end date: '))
month = int(input('Enter the month of the end date: '))
day = int(input('Enter the day of the end date: '))
hour = int(input('Enter the hour of the end date: '))
minute = int(input('Enter the minute of the end date: '))
second = int(input('Enter the second of the end date (a little tricky): '))
future = datetime.datetime(year, month, day, hour, minute, second)
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
difference = future - present
if present >= future:
break
print(difference)
print('Time reached!')
You can use the seconds from a timedelta from subtracting two dates to calculate the days, hours, minutes and seconds like this:
from datetime import datetime
import time
totalSecs = 1 #So the while loop doesn't stop immidiately
while totalSecs > 0:
startDate = datetime.now() #Can be any date
endDate = datetime(2021, 12, 25)
delta = endDate - startDate
totalSecs = delta.total_seconds()
days = divmod(totalSecs, 86400)
hrs = divmod(days[1], 3600)
mins = divmod(hrs[1], 60)
seconds = divmod(mins[1], 1)
print("{:02d}:{:02d}:{:02d}:{:02d}".format(int(days[0]), int(hrs[0]), int(mins[0]), int(seconds[0]))) #Zero pad all the numbers
time.sleep(1) #Print every second.
Thank you all for your replies, i've done a mistake when i made the post. Is not from a date. Is a countdown in day,hours,minutes,seconds from a certain amount of seconds. Let's say i've got 31104000 seconds and i want to print how many days,hours,minutes,seconds left from that amount of seconds.
The code i've got now is a bit trivial and i can't print seconds in realtime.
def SecondToDHM(time):
if time < 60:
return "%.2f %s" % (time, SECOND)
second = int(time % 60)
minute = int((time / 60) % 60)
hour = int((time / 60) / 60) % 24
day = int(int((time / 60) / 60) / 24)
text = ""
if day > 0:
text += str(day) + DAY
text += " "
if hour > 0:
text += str(hour) + HOUR
text += " "
if minute > 0:
text += str(minute) + MINUTE
text += " "
if second > 0:
text += str(second) + SECOND
return text
import datetime
a = datetime.datetime.now()
"%s:%s.%s" % (a.minute, a.second, str(a.microsecond))

Execute function X amount of times between two dates, how would I do it?

If I was able to execute a function a (user-specified) amount of time between two dates, how would I do it?
Am I on the right track?
from datetime import date, datetime
from upload import *
current_time = datetime.utcnow()
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)
imageposts = []
post_limit = 0
for imagepost in imageposts:
if start_time <= current_time & current.time <= end_time & post_limit <= 3:
try:
upload()
postlimit += 1
except:
print('Current time is not between times')
Try this:
from datetime import datetime
from upload import *
current_time = datetime.utcnow()
year, month, day = current_time.year, current_time.month, current_time.day
start_time = datetime(year, month, day, 17)
end_time = datetime(year, month, day, 20, 59, 59)
imageposts = []
post_limit = 0
for imagepost in imageposts:
if start_time <= current.time <= end_time and post_limit <= 3:
try:
upload()
post_limit += 1
except:
print('Current time is not between times')

Getting number of Hours between a Date-Time Range in Python

So I'm trying to print the total hours in intervals between a start date and an end date in python as follows:
#app.route('/test/')
def test():
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def daterange(start_date_time, end_date_time):
for n in range(int ((end_date_time - start_date_time).days)):
yield start_date_time + timedelta(n)
for single_date in daterange(start_date_time, end_date_time):
def get_delta(start_date_time, end_date_time):
delta = end_date_time - start_date_time
return delta
# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
currtime = start_date_time + timedelta(hours=i)
print (currtime)
return ("done")
By This i'm only managing to get the first 24 Hours from the selected date, but I wish to keep on counting and get all hours till the selected end date.
You might be overthinking it.
from datetime import datetime, timedelta
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def get_delta(l, r):
return abs(int((l-r).total_seconds())) / 3600
for h in range(int(get_delta(start_date_time, end_date_time))):
print((start_date_time + timedelta(0, h*3600)).strftime(date_format))

Categories

Resources