print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = datetime.time(time1h,time1m,time1s)
time2 = datetime.time(time2h,time2m,time2s)
diff = datetime.timedelta(hours=(time2.hour - time1.hour), minutes=(time2.minute - time1.minute), seconds=(time2.second - time1.second))
print(diff)
I am trying to print the results from the diff variable separately from each other so I can format it like
"You ran for (diffhours) hours, (diffminutes) minutes, and (diffseconds) seconds"
Alternatively you could do something like this
output_string = str(diff).split(':')
print("You ran for {} hours, {} minutes, and {} seconds".format(*output_string))
While you can use diff.seconds and then carry out various calculations to convert it to hours and minutes as suggested in the other answers, it's also possible to convert diff to a string and process it that way:
diff = str(diff).split(':') # diff will be something like 1:01:23
print(f'You ran for {diff[0]} hours, {diff[1]} minutes and {diff[2]} seconds')
Example output:
You ran for 1 hours, 01 minutes and 01 seconds
Here is the code:
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = timedelta(hours=time1h, minutes=time1m, seconds=time1s)
time2 = timedelta(hours=time2h, minutes=time2m, seconds=time2s)
diff = time2-time1
total_sec = diff.total_seconds()
h = int(total_sec // 3600)
total_sec = total_sec % 3600
m = int(total_sec // 60)
s = int(total_sec % 60)
print(f"You ran for {h} hours, {m} minutes, and {s} seconds")
Related
My code right here emits a strange output, it gives me the second part of inp_a even though I didn`t ask for it. couldn't find the reason why.
Thanks in advance for the help
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\nThe day must be one of the weekdays ")
inp_a = inp_a.split(":")
inp_b = inp_b.split(":")
day = day.lower()
if military_time == "AM":
inp_a[0] = inp_a[0]
elif military_time == "PM":
inp_a[0] = int(inp_a[0]) + 12
inp_a[0] = str(inp_a[0])
try:
convert_a1 = int(inp_a[0])
convert_a2 = int(inp_a[1])
convert_b1 = int(inp_b[0])
convert_b2 = int(inp_b[1])
except:
print("-"*50)
print("One of the inputs is incorrect, try again")
while True:
if day == "sunday":
break
elif day == "monday":
break
elif day == "tuesday":
break
elif day == "wednsday":
break
elif day == "thursday":
break
elif day == "friday":
break
elif day == "saturday":
break
else:
print(day,"is not one of the weekdays try again")
quit()
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
result = rl_time + time2add
hh = result // 60
mm = result % hh
The error is in this part of the code:
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
You're calling input again for no reason, and input prompts the user with its argument (in this case inp_a[1], which is the extra output you're seeing). If you enter something it'll do the same thing on the next line with inp_b[1].
Here's a fixed version of the full thing -- you can simplify a lot by just doing the int conversion once, rather than converting to int, converting back to str, back to int, etc. You also had your while loop in the wrong spot if the intent is to re-prompt the user for new values when something is incorrect.
while True:
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\n"
"The day must be one of the weekdays"
).lower()
try:
ah, am = map(int, inp_a.split(":"))
bh, bm = map(int, inp_b.split(":"))
except (TypeError, ValueError):
print("Time must be entered as HH:MM")
continue
if day not in ("monday", "tuesday", "wednesday", "thursday", "friday"):
print(f"{day.title()} is not one of the weekdays, try again.")
continue
break
if military_time == "PM":
ah += 12
rl_time = ah * 60 + am
time2add = bh * 60 + bm
result = rl_time + time2add
hh, mm = divmod(result, 60)
This is my code to find the time difference. You input hour and time of your preference. Remaining time is calculated by finding the difference between your input and current time but it is not working for me.
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
print("Set Time: ", set_time)
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = set_time - current_time
print(dif)
I am able to get the set time and current time, but not the difference.
This is the output of the program:
Enter hour: 10
Enter minutes: 30
Set Time: 10:30
Current Time: 11:14
You are actually subtracting string from datetime, so convert the first input time to datetime first
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
the_time = datetime.strptime(set_time,'%H:%M')
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = the_time - current_time
print(dif)
I'm trying to add time and have the output as hh:mm:ss, but when datetime gets over 24 hours it becomes x Days, hh:mm:ss. Is there anyway to only have hh:mm:ss greater than 24 hours?
import datetime
from datetime import timedelta
# intro
print("Welcome to TimeCalc")
print("Calculating Durations")
clear = True
while clear == True:
# first input
firstNumber = True
while firstNumber == True:
time_1 = input("Please enter a time [hh:mm:ss] including 0s: ")
if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60:
hours_1 = time_1[:-6]
minutes_1 = time_1[-5:-3]
seconds_1 = time_1[-2:]
hours_1 = int(hours_1)
minutes_1 = int(minutes_1)
seconds_1 = int(seconds_1)
firstNumber = False
else:
print("Invalid Syntax")
time_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
cont = True
while cont == True:
# second input
secondNumber = True
while secondNumber == True:
time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ")
if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60:
hours_2 = time_2[:-6]
minutes_2 = time_2[-5:-3]
seconds_2 = time_2[-2:]
hours_2 = int(hours_2)
minutes_2 = int(minutes_2)
seconds_2 = int(seconds_2)
secondNumber = False
else:
print("Invalid Syntax")
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
total = time_1 + time_2
print("The total duration is: " + str(total))
# continue, clear, or exit
choice = input("Continue: Y | Clear: N | Exit: X: ")
if choice == "Y" or choice == "y":
time_1 = total
elif choice == "N" or choice == "n":
cont = False
elif choice == "X" or choice == "x":
quit()
after total variable, can you try to put this code, maybe this is not a super solution but it works
seconds = int(total.total_seconds())
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("The total duration is: {h:02d}:{m:02d}:{s:02d}".format(h=hours,
m=minutes, s=seconds))
Use the .strftime() method to format your datetime string.
For example,
>>> import datetime
>>> d = datetime.delta(hours=1)
>>> dt = datetime.datetime(2017,10,30,23,10,10) + d
>>> dt.strftime("%H:%M:%S")
'00:10:10'
Hope it help.
Whenever I type n for night, it only plays the day cycle. I'm generally new to python and would appreciate help.
userinput = input("Is it day (d) or night (n) - type d or n:")
n = win.setBackground("MidnightBlue")
d = win.setBackground("DeepSkyBlue")
n_message = ("Time has been set to night!")
d_message = ("Time has been set to day!")
for character in range(1333):
if userinput == n:
print(n_message)
win.setBackground("MidnightBlue")
update(30)
sun.undraw()
moon = Circle(Point(100, 100), 90)
moon.setFill("LightYellow")
moon.draw(win)
moon_cover = Circle(Point(140, 90), 60)
moon_cover.setFill("MidnightBlue")
moon_cover.setOutline("MidnightBlue")
moon_cover.draw(win)
else:
print(d_message)
update(30)
win.setBackground("DeepSkyBlue")
break
How can I create a countdown clock in Python that looks like 00:00 (min & sec) which is on a line of its own. Every time it decreases by one actual second then the old timer should be replaced on its line with a new timer that is one second lower:
01:00 becomes 00:59 and it actually hits 00:00.
Here is a basic timer I started with but want to transform:
def countdown(t):
import time
print('This window will remain open for 3 more seconds...')
while t >= 0:
print(t, end='...')
time.sleep(1)
t -= 1
print('Goodbye! \n \n \n \n \n')
t=3
I also want to make sure that anything after Goodbye! (which would most likely be outside of the function) will be on its own line.
RESULT: 3...2...1...0...Goodbye!
I know this is similar to other countdown questions but I believe that it has its own twist.
Apart from formatting your time as minutes and seconds, you'll need to print a carriage return. Set end to \r:
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print('Goodbye!\n\n\n\n\n')
This ensures that the next print overwrites the last line printed:
Here is the code which counts from 01:05 to 00:00 in MM:SS format.
Python 3 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j), end="\r")
else:
print(str(k)+str(i)+":"+str(k)+str(j), end="\r")
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("Goodbye!", end="\r")
time.sleep(1)
countdown(1,5) #countdown(min,sec)
Python 2 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print "\r"+str(k)+str(i)+":"+str(j),
else:
print "\r"+str(k)+str(i)+":"+str(k)+str(j),
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print "\rGoodbye!"
time.sleep(1)
countdown(1,5) #countdown(min,sec)
For the simplicity, this code is able to say you how long it takes until the next desired time, which might be whatever you want to do in your program. In your case, this is a kind of countdown timer.
from datetime import datetime
x=datetime.today()
y=x.replace(day=x.day+1, hour=3, minute=1, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
second = (secs % 60)
minut = (secs / 60) % 60
hour = (secs / 3600)
print ("Seconds: %s " % (second))
print ("Minute: %s " % (minut))
print ("Hour: %s" % (hour))
print ("Time is %s:%s:%s" % (hour, minut, second))
Then, output is as follows:
Seconds: 50
Minute: 32
Hour: 12
Time is 12:32:50
Good luck with your coding.
Maybe this link will help:
Making a Timer in Python 3
And look at my answer, it is same for your too!
Anyway, here is answer:
import time
import os
hour = int(input('Enter any amount of hours you want -+==> '))
minute = int(input('Enter any amount of minutes you want -+==> '))
second = int(input('Enter any amount of seconds you want -+==> '))
time = hour*10800 + minute*3600 + second*60
print('{}:{}:{}'.format(hour,minute,second))
while time > 0:
time = time - 1
seconds = (time // 60) % 60
minutes = (time // 3600)
hours = (time // 10800)
print('Time Left -+==> ',hours,':',minutes,':',seconds,)
os.system("CLS")
if time == 0:
print('Time Is Over!')
Input:
Enter any amount of hours you want -+==> 0
Enter any amount of minutes you want -+==> 0
Enter any amount of seconds you want -+==> 10
Output # All are on the same line
Time Left -+==> 0:0:10
Time Left -+==> 0:0:9
Time Left -+==> 0:0:8
Time Left -+==> 0:0:7
Time Left -+==> 0:0:6
Time Left -+==> 0:0:5
Time Left -+==> 0:0:4
Time Left -+==> 0:0:3
Time Left -+==> 0:0:2
Time Left -+==> 0:0:1
Time Left -+==> 0:0:0
Time Is Over!
import time
import sys
print(' ')
print('Countdown Timer, By Adam Gay')
print(' ')
print('Instructions: Input time to countdown from.')
print(' ')
c=':'
hourz=input('Hours: ')
minz=input('Minutes: ')
secz=input('Seconds: ')
print(' ')
hour=int(hourz)
min=int(minz)
sec=int(secz)
while hour > -1:
while min > -1:
while sec > 0:
sec=sec-1
time.sleep(1)
sec1 = ('%02.f' % sec) # format
min1 = ('%02.f' % min)
hour1 = ('%02.f' % hour)
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + str(sec1))
min=min-1
sec=60
hour=hour-1
min=59
Print('Countdown Complete.')
time.sleep(30)