How to translate exercise into a time based value? - python

I have started taking a beginner class in python but cannot wrap my head around translating this exercise into time based value:
Exercise:
"You set off at 8:12am and jog for 1km at 12:10 per kilometre, then 5km at the pace 10:15 per kilometre and then 1km at 12:10 per kilometre, what time do you finish?"
What I have so far -
import datetime
starttime = datetime.time(8,12,0)
print(starttime)
firstkm = 1
firstpace = 12.10
firststint = firstkm * firstpace
print(firststint)
secondkm = 5
secondpace = 10.15
secondstint = secondkm * secondpace
print(secondstint)
thirdkm = 1
thirdpace = 12.10
thirdstint = thirdkm * thirdpace
print(thirdstint)
runtime = firststint + secondstint + thirdstint
print(runtime)
I attempted to multiply time based values and also tried converting at the end of the process. I watched various videos that helped with the time based items but nothing seemed to discuss multiplying values, what am I missing?

You can add hours/minutes/... to a datetime object by adding a timedelta.
from datetime import date, datetime, time, timedelta
starttime = datetime.combine(date.today(), time(8, 12, 0))
print(starttime.time())
h = 0.50 // a half hour. // TODO calculate a correct elapsed time
endtime = starttime + timedelta(hours=h)
print(endtime.time())
By the way, the elapsed hour seems be firstkm / firstpace + secondkm / secondpace + thirdkm / thirdpace

Related

How can I correctly import strptime in order to calculate the difference between 2 given times in python

import datetime
a = int(input("sekund1"))
b = int(input("sekund2"))
time1 = datetime.strptime(a,"%H%M")
time2 = datetime.strptime(b,"%H%M")
diff = time1 -time2
diff.total_seconds()/3600
I am trying to create a "calculator" for given times in python, my knowledge in the language is very limited and this is how far I've managed to come.
Although this is very limited as it will only subtract given seconds, I am trying to subtract 2 given times in the format HH:MM:SS, but this is where I come at a stop.
I get an error
module 'datetime' has no attribute 'strptime'
I am not sure I understand what you want to do but here my interpretation of it, in the simplest way I could think of.
import datetime
a = input("a [HH:MM:SS] : ")
b = input("b [HH:MM:SS] : ")
a_from_str_to_list = a.split(':')
b_from_str_to_list = b.split(':')
a_seconds = ( int(a_from_str_to_list[0]) * 3600 ) + ( int(a_from_str_to_list[1]) * 60 ) + int(a_from_str_to_list[2])
b_seconds = ( int(b_from_str_to_list[0]) * 3600 ) + ( int(b_from_str_to_list[1]) * 60 ) + int(b_from_str_to_list[2])
c_secondds = a_seconds - b_seconds
t = str(datetime.timedelta(seconds = c_secondds))
print(t)
given 01:01:13 and 00:00:13 as input it would print 01:01:00
I tried out your code and found a few tweaks that needed to be made. Following is a code snippet with those tweaks.
from datetime import datetime # To make "datetime.strptime()" work
a = str(input("sekund1 "))
b = str(input("sekund2 "))
time1 = datetime.strptime(a,"%H:%M") # Was missing the ":" symbol
time2 = datetime.strptime(b,"%H:%M") # Was missing the ":" symbol
diff = time1 -time2
print("Difference in hours:", diff.total_seconds()/3600)
Here was a sample of output.
#Una:~/Python_Programs/Seconds$ python3 Diff.py
sekund1 12:45
sekund2 10:45
Difference in hours: 2.0
Give that a try.

How to find the difference between two times

I'm trying to figure out a way to take two times from the same day and figure out the difference between them. So far shown in the code below I have converted both of the given times into Int Vars and split the strings to retrieve the information. This works well but when the clock in values minute is higher than the clock out value it proceeds to give a negative value in minute slot of the output.
My current code is:
from datetime import datetime
now = datetime.now()
clocked_in = now.strftime("%H:%M")
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
hours = out_hh - in_hh
mins = out_mm - in_mm
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
if the clocked in value is 12:30 and the clocked out value is 18:10
the output is:
6:-20
the output needs to be converted back into a stand time format when everything is done H:M:S
Thanks for you assistance and sorry for the lack of quality code. Im still learning! :D
First, in order to fix your code, you need to convert both time to minutes, compute the difference and then convert it back to hours and minutes:
clocked_in = '12:30'
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
diff = (in_hh * 60 + in_mm) - (out_hh * 60 + out_mm)
hours, mins = divmod(abs(diff) ,60)
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
# 5: 40
Better way to implement the time difference:
import time
import datetime
t1 = datetime.datetime.now()
time.sleep(5)
t2 = datetime.datetime.now()
diff = t2 - t1
print(str(diff))
Output:
#h:mm:ss
0:00:05.013823
Probably the most reliable way is to represent the times a datetime objects, and then take one from the other which will give you a timedelta.
from datetime import datetime
clock_in = datetime.now()
clock_out = clock_in.replace(hour=18, minute=10)
seconds_diff = abs((clock_out - clock_in).total_seconds())
hours, minutes = seconds_diff // 3600, (seconds_diff // 60) % 60
print(f"{hours}:{minutes}")

add 15 minutes in a YYYYMMDDHHMMSS format variable

I have a variable holding information about time (not current time) in the YYYYMMDDHHMMSS format.
I have a starting point and a finish point. Lets say '20210419000100' and '20210419130100'. Thats 13 hours from start to finish.
I want to save a string of this time for every 15 mins. ie we start at '20210419000100' and 15 mins later it will be '20210419001600'.
Obviously its not always +1500. I know its a long shot, but is there a tool for that or how could i do that in a generic way that would work with any starting point I would choose? It could be done only in HHMMSS format if its easier but if possible I would like the year/month/day to change, too.
I am more interested in a python solution.
python-dateutil to the rescue!
from dateutil import parser, relativedelta
START_DATE = '20210419000100'
END_DATE = '20210419130100'
start = parser.parse(START_DATE)
end = parser.parse(END_DATE)
while start < end:
print(start.strftime("%Y%m%d%H%M%S"))
start += relativedelta.relativedelta(minutes=15)
No need to install other dependencies, you can use python's standard datetime module
from datetime import datetime, timedelta
time_str = '20210419000100'
time_obj = datetime.strptime(time_str, '%Y%m%d%H%M%S')
print(time_obj)
# 2021-04-19 00:01:00
# If you want to add hours or minutes
def seconds(h = 0, m = 0, s = 0):
return h * 3600 + m * 60 + s
time_obj += timedelta(0, seconds(m=15)) # days, seconds
print(time_obj)
# 2021-04-19 00:16:00
# In case you want to convert it back
new_time_str = time_obj.strftime("%Y%m%d%H%M%S")
print(new_time_str)
# 20210419001600

In Python, I want to subtract a time period from within a time period

I want to calculate hours of work during a day, and subtract lunchtime from that time. So somebody clocks in at 8:00, takes a lunch from 12:00 to 12:30, and finish at 16:00.
Lunchtime is configured in a settings table, with start-time and end-time.
So in a nutshell I want to calculate this:
endtime minus starttime = n hours:minutes of work, minus lunchtime (= 12:30 - 12:00 = 30 minutes)
How can I calculate this in Python without making this a hardcoded thing?
Help would be much appreciated
cheers
You can do it with Python datetime:
import datetime as dt
def work_time(start, end, lunch=[], format_='%H:%M'):
""" Calculate the hours worked in a day.
"""
start_dt = dt.datetime.strptime(start, format_)
end_dt = dt.datetime.strptime(end, format_)
if lunch:
lunch_start_dt = dt.datetime.strptime(lunch[0], format_)
lunch_end_dt = dt.datetime.strptime(lunch[1], format_)
lunch_duration = lunch_end_dt - lunch_start_dt
else:
lunch_duration = dt.timedelta(0)
elapsed = end_dt - start_dt - lunch_duration
hours = elapsed.seconds / 3600
return hours
>>> work_time('8:00', '16:00', lunch=['12:00', '12:30'])
7.5
The documentation for datetime provides more information on specific formatting and how to use timedeltas to perform operations on datetime and time objects.

Calculating the times into minutes

I am working on my python code as I want to calulcating on the program time to convert it into minutes. When the program start at 12:00AM and my current time show as 1:00AM. The end time show for the program is 6:00AM, so I want to work out between 1:00AM and 6:00AM to take it away then multiply it by 60 to convert it into minutes.
Example: 6 take away 1 which is 5 then I want to multply it by 60 which it is 300 minutes.
Here is the code:
current_time = int(time.strftime("%M"))
prog_width = self.getControl(int(program_id)).getWidth()
prog_length = int(prog_width) / 11.4 - current_time
prog_length = str(prog_length)
prog_length = prog_length.replace('.0', '')
prog_length = int(prog_length)
print prog_length
Can you please show me an example of how I can calculating between 1:00AM and 6:00AM to take it away then convert it into minutes when multply by 60?
You can use the datetime module
from datetime import timedelta
start = timedelta(hours=1)
end = timedelta(hours=6)
duration = end - start
print duration.total_seconds() / 60

Categories

Resources