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.
Related
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")
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)
After it validates the date and time for the appointment I need to make sure it doesn't overlap with a pre-existing appointment in the appontmentList[] and I'm stuck as to where to start.
I'm thinking somewhere along the lines of:
for x in appointmentList:
if start <= x:
print('invalid, overlapping appointment! ')
else:
break
See my full code below:
appointmentList = []
def add_sort():
choice = input ('Add item to diary (a) or sort (s)')
if choice == 's':
print ('sorting')
sortRecords()
elif choice == 'a':
print ('adding')
add_record()
else:
add_sort()
def add_record():
while True:
Priority = input ('What is the priority of your appointment? ')
if 'low' != Priority != 'Low' and 'high' != Priority != 'High':
print('invalid, must be low or high! ')
else:
break
# is_valid_date():
while True:
dt = input('enter date of appointment in dd/mm/yyyy format. ')
day_string, month_string, year_string = dt.split('/')
day = int(day_string)
month = int(month_string)
year = int(year_string)
if month in [1, 3, 5, 7, 8, 10, 12]:
max_days=31
elif month in [4, 6, 9 ,11]:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print('invalid, enter a number between 1 - 12')
elif day<1 or day>max_days:
print('invalid, check day')
elif 10000 > year <2022:
print('invalid, enter a year greater than 2021')
# is_valid_time():
Start = int(input('What is the starting time of your appointment? '))
if Start < 7 or Start > 22:
print('invalid, enter a time between 7 - 22. ')
End = int(input('What is the ending time of your appointment? '))
if End < Start or End > 22:
print('invalid, please choose a time after starting time. ')
# def is_concurrent():
from datetime import datetime
start = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(Start), '%H').time())
end = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(End), '%H').time())
current = datetime.now()
if start < current:
print('invalid, enter a time & date in the future! ')
elif end < start:
print('invalid, enter an end time after the start time! ')
else:
break
Subject = input ('What is the subject of your appointment?')
appointment = ['{}; {}; {}; {}; {};'.format(Priority, dt, Start, End, Subject)]
appointmentList.append(appointment)
print(appointmentList)
add_sort()
def sortRecords():
choice = input ('Do you want to sort by priority or time or END. ')
if choice.lower() == 'priority':
print ('priority')
print(appointmentList)
plist = sorted(appointmentList, key = lambda x: x[0])
print(plist)
sortRecords()
elif choice.lower() == 'time':
print('time')
print(appointmentList)
tlist = sorted(appointmentList, key = lambda x: x[1])
print(tlist)
sortRecords()
elif choice.lower() != 'end':
print ('invalid')
sortRecords()
add_sort()
for x in appointmentList:
print (x)
add_sort()
the idea is the user inputs an appointment with priority, date, start time, end time and subject, it first prints like this '[['high; 15/7/2022; 8; 9; Hello;']]' and then saves it to the appointment list, I need to find out how to see if a previously made appointment overlaps with the appointment the user is currently trying to enter.
In my current python program which shows all possible combinations, it does not show the multiples of 10 (10,20,30,40,etc.) and I don't understand why, I am using the itertools library don't know if there is something that does this? I have looked online and I haven't found anything like it so maybe it has something to do with my installation of it? Anyway, here is the code.
import itertools
from pynput.keyboard import Controller
import time
keyboard = Controller()
loop = True
a = 1
input("Welcome to the Password Possibilities Test")
input("This test will tell you how many possible")
input("combinations a password can have")
input("*all answers must start with an uppercase*")
num_length = 0
alpha_length = 0
sym_length = 0
num = input("So lets start does your password have numbers?\n")
alpha = input("Does it have letters?\n")
sym = input("Does it have symbols?\n")
long = input("Do you know how long the password is?\n")
possibilities = []
if long == "Yes":
length = input("How long is the password?\n")
elif long == "No":
print("Then we will go off of the average password length which is 8\n")
length = 8
if num == "Yes":
num_length = 10
possibilities.append(0)
possibilities.append(1)
possibilities.append(2)
possibilities.append(3)
possibilities.append(4)
possibilities.append(5)
possibilities.append(6)
possibilities.append(7)
possibilities.append(8)
possibilities.append(9)
else:
num_length = 0
if alpha == "Yes":
alpha_length = 52
possibilities.append("a")
possibilities.append("b")
possibilities.append("c")
possibilities.append("d")
possibilities.append("e")
possibilities.append("f")
possibilities.append("g")
possibilities.append("h")
possibilities.append("i")
possibilities.append("j")
possibilities.append("k")
possibilities.append("l")
possibilities.append("m")
possibilities.append("n")
possibilities.append("o")
possibilities.append("p")
possibilities.append("q")
possibilities.append("r")
possibilities.append("s")
possibilities.append("t")
possibilities.append("u")
possibilities.append("v")
possibilities.append("w")
possibilities.append("x")
possibilities.append("y")
possibilities.append("z")
possibilities.append("A")
possibilities.append("B")
possibilities.append("C")
possibilities.append("D")
possibilities.append("E")
possibilities.append("F")
possibilities.append("G")
possibilities.append("H")
possibilities.append("I")
possibilities.append("J")
possibilities.append("K")
possibilities.append("L")
possibilities.append("M")
possibilities.append("N")
possibilities.append("O")
possibilities.append("P")
possibilities.append("Q")
possibilities.append("R")
possibilities.append("S")
possibilities.append("T")
possibilities.append("U")
possibilities.append("V")
possibilities.append("W")
possibilities.append("X")
possibilities.append("Y")
possibilities.append("Z")
else:
alpha_length = 0
if sym == "Yes":
sym_length = 32
possibilities.append("!")
possibilities.append("#")
possibilities.append("#")
possibilities.append("$")
possibilities.append("%")
possibilities.append("^")
possibilities.append("&")
possibilities.append("*")
possibilities.append("(")
possibilities.append(")")
possibilities.append("_")
possibilities.append("+")
possibilities.append("{")
possibilities.append("}")
possibilities.append("|")
possibilities.append(":")
possibilities.append("\\")
possibilities.append("?")
possibilities.append(">")
possibilities.append("<")
possibilities.append("~")
possibilities.append("`")
possibilities.append("[")
possibilities.append("]")
possibilities.append("\"")
possibilities.append(";")
possibilities.append("'")
possibilities.append("/")
possibilities.append(".")
possibilities.append(",")
possibilities.append("`")
else:
sym_length = 0
num_length = int(num_length)
alpha_length = int(alpha_length)
sym_length = int(sym_length)
length = int(length)
calc = num_length + alpha_length + sym_length
final = pow(calc,length)
print("This password has ",final, "possibilities")
input("Click the ENTER key to view all of the combonations")
time.sleep(2)
for i in itertools.combinations_with_replacement(possibilities,length):
print(*i, sep='')
print("This password has ",final, "possibilities")
exit = input("Would you like to exit?\n")
if exit == "Yes":
pass
elif exit == "No":
while loop == True:
a = 1
When you would like to show all possible combinations you mean about the mathematical concept of the permutation with the repetitions. In python in the itertools library there is only permutations that it is like in mathematics the permutation without the repetitions. In python you can use in exchange for it the itertools.product. The full functioning code I enclose below:
import itertools
from pynput.keyboard import Controller
import time
keyboard = Controller()
loop = True
a = 1
input("Welcome to the Password Possibilities Test")
input("This test will tell you how many possible")
input("combinations a password can have")
input("*all answers must start with an uppercase*")
num_length = 0
alpha_length = 0
sym_length = 0
num = input("So lets start does your password have numbers?\n")
alpha = input("Does it have letters?\n")
sym = input("Does it have symbols?\n")
long = input("Do you know how long the password is?\n")
possibilities = []
if long == "Yes":
length = input("How long is the password?\n")
elif long == "No":
print("Then we will go off of the average password length which is 8\n")
length = 8
if num == "Yes":
num_length = 10
possibilities.append("0")
possibilities.append("1")
possibilities.append("2")
possibilities.append("3")
possibilities.append("4")
possibilities.append("5")
possibilities.append("6")
possibilities.append("7")
possibilities.append("8")
possibilities.append("9")
else:
num_length = 0
if alpha == "Yes":
alpha_length = 52
possibilities.append("a")
possibilities.append("b")
possibilities.append("c")
possibilities.append("d")
possibilities.append("e")
possibilities.append("f")
possibilities.append("g")
possibilities.append("h")
possibilities.append("i")
possibilities.append("j")
possibilities.append("k")
possibilities.append("l")
possibilities.append("m")
possibilities.append("n")
possibilities.append("o")
possibilities.append("p")
possibilities.append("q")
possibilities.append("r")
possibilities.append("s")
possibilities.append("t")
possibilities.append("u")
possibilities.append("v")
possibilities.append("w")
possibilities.append("x")
possibilities.append("y")
possibilities.append("z")
possibilities.append("A")
possibilities.append("B")
possibilities.append("C")
possibilities.append("D")
possibilities.append("E")
possibilities.append("F")
possibilities.append("G")
possibilities.append("H")
possibilities.append("I")
possibilities.append("J")
possibilities.append("K")
possibilities.append("L")
possibilities.append("M")
possibilities.append("N")
possibilities.append("O")
possibilities.append("P")
possibilities.append("Q")
possibilities.append("R")
possibilities.append("S")
possibilities.append("T")
possibilities.append("U")
possibilities.append("V")
possibilities.append("W")
possibilities.append("X")
possibilities.append("Y")
possibilities.append("Z")
else:
alpha_length = 0
if sym == "Yes":
sym_length = 32
possibilities.append("!")
possibilities.append("#")
possibilities.append("#")
possibilities.append("$")
possibilities.append("%")
possibilities.append("^")
possibilities.append("&")
possibilities.append("*")
possibilities.append("(")
possibilities.append(")")
possibilities.append("_")
possibilities.append("+")
possibilities.append("{")
possibilities.append("}")
possibilities.append("|")
possibilities.append(":")
possibilities.append("\\")
possibilities.append("?")
possibilities.append(">")
possibilities.append("<")
possibilities.append("~")
possibilities.append("`")
possibilities.append("[")
possibilities.append("]")
possibilities.append("\"")
possibilities.append(";")
possibilities.append("'")
possibilities.append("/")
possibilities.append(".")
possibilities.append(",")
possibilities.append("`")
else:
sym_length = 0
num_length = int(num_length)
alpha_length = int(alpha_length)
sym_length = int(sym_length)
length = int(length)
calc = num_length + alpha_length + sym_length
print(calc)
final = pow(calc,length)
print("This password has ",final, "possibilities")
input("Click the ENTER key to view all of the combonations")
time.sleep(2)
for i in itertools.product(possibilities, repeat = length):
print(*i, sep='')
print("This password has ",final, "possibilities")
exit = input("Would you like to exit?\n")
if exit == "Yes":
pass
elif exit == "No":
while loop == True:
a = 1
I am making a code to simulate a dice and do other stuff, but there is a while loop which isn't breaking and I don't know why.
import random
import math
#infinite loop
while True:
while True:
a = 0
#input amount of dice
att_die = raw_input('Attacking dice: ')
def_die = raw_input('Defending dice: ')
#att
#if NaN
if str(att_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a += 1
#def
#if NaN
if str(def_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a +=1
if a == 2:
break
if att_die >= def_die:
no = def_die
else:
no = att_die
print (no)
x = 0
while x <= no:
att_loss = 0
def_loss = 0
roll_att = random.randint(1,6)
roll_def = random.randint(1,6)
if roll_att <= roll_def:
att_loss += 1
elif roll_att == roll_def:
att_loss += 1
else:
def_loss += 1
x += 1
print(x)
print('Att: -' + str(att_loss) + '\nDef: -' + str(def_loss))
everything works up until the last while loop, which just continuously outputs the value of x increasing.
Any help on how to fix this would be appreciated.
Thanks in advance
no is a str, not an int. x is an int. In Python2, ints are always compare less than strs:
In [187]: 9999 < '1'
Out[187]: True
The solution is to convert the str no into an int:
no = int(no)
In [188]: 9999 < int('1')
Out[188]: False
Note that in Python3, comparing an int with a str raises a TypeError, which will save many a programmer from this pitfall.
Here's a refactored version:
import random
import math
DIE_SIDES = 6
WINNING_ATTACK_ODDS = 0.5 * (DIE_SIDES - 1) / DIE_SIDES
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def attack():
"""
Does the attacker win?
"""
return random.random() < WINNING_ATTACK_ODDS
def main():
while True:
att_die = get_int("Attacking dice: ")
def_die = get_int("Defending dice: ")
rolls = min(att_die, def_die)
def_loss = sum(attack() for _ in range(rolls))
att_loss = rolls - def_loss
print("Att: -{}\nDef: -{}".format(att_loss, def_loss))
if __name__=="__main__":
main()