Calculate time between time-1 to time-2? - python

enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.

The datetime and timedelta class from the built-in datetime module is what you need.
from datetime import datetime
# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')
# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)

Simplest and most direct may be something like:
def getime(prom):
"""Prompt for input, return minutes since midnight"""
s = raw_input('Enter time-%s (hh:mm): ' % prom)
sh, sm = s.split(':')
return int(sm) + 60 * int(sh)
time1 = getime('1')
time2 = getime('2')
diff = time2 - time1
print "Difference: %d hours and %d minutes" % (diff//60, diff%60)
E.g., a typical run might be:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes

Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.
from time import time
t0 = time()
# do stuff that takes time
print time() - t0

Assuming that the user is entering strings like "01:12", you need to convert (as well as validate) those strings into the number of minutes since 00:00 (e.g., "01:12" is 1*60+12, or 72 minutes), then subtract one from the other. You can then convert the difference in minutes back into a string of the form hh:mm.

Related

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}")

why is not the result 00:00:XX?

i expected like 00:00:0X but 09:00:0X came out how can i do to make 00:00:0X
import time
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
result = time.localtime(count - begin)
print(count - begin)
print(time.strftime('%I:%M:%S', result))
result:
1.0102884769439697
09:00:01
2.0233511924743652
09:00:02
3.0368154048919678
time.time() will give you the number of seconds since 1.1.1970 in UTC.
So begin is a huge number and count will also be a huge number + about 1. Subtracting those will give about 1.
If you pass this to time.time() you'll get 1.1.1970 plus 1 second. Converting to local time (time.localtime()) will give you whatever timezone offset you are. Obviously +9 hours.
What you probably wanted is time.gmtime() and output in 24 hour format. This will work...
import time
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
result = time.gmtime(count - begin)
print(count - begin)
print(time.strftime('%H:%M:%S', result))
but it is semantically incorrect. If you subtract 2 dates, the result is a timespan, not a date. What is the difference?
If someone asks, how old you are, you have a look at the current year and you subtract the year of your birth. Then you say "I'm 25 years old". You don't add 1.1.1970 and say "I'm 1995 years old".
So the following is semantically much better:
import time
from datetime import timedelta
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
timespan = timedelta(seconds=count - begin)
print(timespan)
It shows 09:00:00 because you're in the UTC+9 timezone. For example, I'm in UTC+1 (France) and it shows 01:00:00 for me. Therefore, your code will have different outputs depending on where you run it.
To remove this timezone constraint, simply use datetime.timedelta:
begin = time.time()
while True:
time.sleep(1)
count = time.time()
print(datetime.timedelta(seconds=round(count - begin)))
Output:
0:00:01
0:00:02
0:00:03
0:00:04
0:00:05

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

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

Seconds left to HH:MM

I need to check how many seconds are lef to the nearest HH:MM time in Python (in 24 hour format). For example, now is 10:00 - I need to check 16:30 same day.
If its 18:00 I need to check secods left to the 16:30 next day end so on.
You probably want to use the datetime module, timeldelta is your friend here:
import datetime
def cal_delta_to(hour, minute):
now = datetime.datetime.now()
target = datetime.datetime(*now.timetuple()[0:3], hour=16, minute=30)
if target < now: # if the target is before now, add one day
target += datetime.timedelta(days=1)
diff = now - target
return diff.seconds
Start with simple steps. Programming is usually about breaking down tasks like these into steps.
Get current time. Get next 16:30. Subtract.
# use datetime
from datetime import datetime, timedelta
# get current time
curr = datetime.now()
# create object of nearest 16:30
nearest = datetime(curr.year, curr.month, curr.day, 16, 30)
# stupidly check if it's indeed the next nearest
if nearest < curr:
nearest += timedelta(days=1)
# get diff in seconds
print (nearest - curr).seconds
If your format is ensured, you can easily calculate the seconds of the day:
def seconds_of_day(hhmm):
return int(hhmm[:2])*3600 + int(hhmm[3:])*60
Having done this the comparison is straightforward:
t1 = seconds_of_day('16:30')
t2 = seconds_of_day('10:00')
#t2 = seconds_of_day('18:01')
diff = 86400-t2+t1 if t1<t2 else t1-t2
Use datetime:
import datetime
func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds
You can always get what you want, even in the special 'next day' cases, like in case1 below;
# case1: now is '09:30', check seconds left to the 09:29 next day
>>> (func('09:29')-func('09:30')).seconds
86340
# case2: now is '09:30', check 10:30 the same day
>>> (func('10:30')-func('09:30')).seconds
3600

Categories

Resources