I have this code for my alarm clock program, which checks if the input is of the form HH:MM:SS.
def testing():
try:
alarm = input("> ")
hour = int(alarm[0:2])
minute = int(alarm[3:5])
second = int(alarm[6:8])
if len(alarm) == 8:
print(("\nsets to %s:%s:%s\n" % (hour, minute, second)))
except ValueError:
print("format must be HH:MM:SS")
testing()
testing()
It works fine unless, for example, the input is "00:00:00", in which case the output is "0:0:0" instead of the expected output with each unit padded to two digits. Why is this happening?
Consider the line hour = int(alarm[0:2]) when alarm is "00:00:00":
alarm[0:2] will be "00" and int("00") is the integer 0.
The same happens for minute and second. When you interpolate the values of hour, minute, and second, then the result is "0:0:0".
You can pad the hour, minute, and second values to two digits by changing your print statement to
print(("\nsets to %02d:%02d:%02d\n" % (hour, minute, second)))
Since you are formatting the values into strings, you could do without the conversion from strings to integers:
hour = alarm[0:2]
minute = alarm[3:5]
second = alarm[6:8]
Also, instead of the % operator, I would use str.format() which is a more powerful string formatting method:
print("\nsets to {}:{}:{}\n".format(hour, minute, second))
Change from print(("\nsets to %s:%s:%s\n" % (hour, minute, second)))
Into this format print(("\nsets to %02d:%02d:%02d\n" % (hour, minute, second)))
Now instead of printing 2:0:0 or 0:0:0 you will print 02:00:00 or 00:00:00
Related
I'm trying to convert times from hours, minutes, seconds, to just seconds but I can't figure out why I'm getting the error "could not convert string to float"
tmp1 = t.split('.')[0]
tmp2 = tmp1.split(':')
if len(tmp2)>1:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp1[1])
if len(tmp2)>2:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp2[2])
print(t, tmp1, tmp2, seconds)
02:38.0 02:38.0 ['02', '38'] 9482.0
02:28:28 02:28:28 ['02', '28', '28'] 8908.0
02:10.21 02:10 ['02', '10'] 7802.0
Do not try the second form if the first is executed:
if len(tmp2)>2:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp2[2])
elif len(tmp2)>1:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp1[1])
tmp1[1] is the second character of the string tmp1. If that is a : or other non-digit, it won't be able to convert it to a float.
If your input is 2:34.56, tmp[1] is equal to : when you run
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp1[1])
You likely are intending to run the len(tmp2)>2 condition only when it does not run the other condition. One solution would be to use equals instead of greater than.
if len(tmp2) == 2:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp1[1])
elif len(tmp2) == 3:
seconds = 60.0*60.0*float(tmp2[0])+60.0*float(tmp2[1])+float(tmp2[2])
The other option would be to swap the conditions (as #Błotosmętek has done in their answer). Either way, you should use elif (else if) instead of if for the second condition so that the second condition won't run if the first condition has run.
I'm a pretty new python user, working on a project that will be used by people who won't really understand how picky python can be about inputs. For the program, I need to get user input telling me how long a video is(minutes and seconds), and then I need to subtract a minute and eight seconds from that length, then print it. Is there a way I could process an input such as "5 minutes and 30 seconds"?
One possibility is to check each substring in the user's input and assign them to values:
s = input("video length? ")
minutes, seconds = [int(x) for x in s.split() if x.isdigit()]
The cast int(x) will save them as integers if desired:
print(minutes) # 5
print(seconds) # 30
Or a regular expression solution may be:
import re
minutes, seconds = map(int, re.findall('\d+', s))
print(minutes) # 5
print(seconds) # 30
Now you have the values to perform the resulting time calculation:
import datetime
# here, 100,1,1 are just placeholder values for year, month, day that are required to create a datetime object
usertime = datetime.datetime(100,1,1, minute=minutes, second=seconds)
calculation = usertime - datetime.timedelta(minutes=1, seconds=8)
Now you can display the result of the time calculation however you like:
print('{minutes} minutes and {seconds} seconds'.format(minutes=calculation.minute, seconds=calculation.second))
# 4 minutes and 22 seconds
You could use a regular expression if the format will always be the same (but it probably will not), then convert the appropriate string to an integer/ double.
I think that you are going about this incorrectly. It would be best to have two separate input fields that only accept integers. One for minutes and one for seconds. If you want more precision (i.e milliseconds) then just include another input field.
The main problem here is the format in which you will accept the input. You could force the user to input the time in just one format, for example, hours:minutes:seconds, in that case, the code below will calculate the total seconds:
inp = input('Video duration: ').split(':')
hours = 0
mins = 0
secs = 0
if len(inp) >= 3:
hours = int(inp[-3])
if len(inp) >= 2:
mins = int(inp[-2])
secs = int(inp[-1])
total_secs = hours * 3600 + mins * 60 + secs - 68
I oversimplified the code, it doesnt avoid user errors and edge cases
You can try :
import re
from datetime import datetime, timedelta
question = "How long is the video (mm:ss)? "
how_long = input(question).strip()
while not re.match(r"^[0-5]?\d:[0-5]?\d$", how_long): # regex to check if mm:ss digits are in range 0-5
how_long = input("Wrong format. " + question).strip()
mm_ss = how_long.split(":")
how_long_obj = datetime.strptime(f"{mm_ss[0]}:{mm_ss[1]}", '%M:%S')
print(f"{how_long_obj - timedelta(seconds=68):%M:%S}")
Output:
How long is the video (mm:ss)? 22:33
21:25
Python3 Demo - (Please turn Interactive mode On)
I am new to python, trying to figure this one out:
Inputs are:
1.One integer for local time in Eastern time zone
2.One string containing “am” or “pm”.
3.All other variations such as Am, Pm.
4.AM, PM should result in a message stating that input format is not right
Outputs are:
___ EST is ___Central Time(CT)
___ EST is ___Mountain Time(MT)
___EST is___Pacific Time(PT)
Here is the code so far :
#Function 1:
def time_in_24h(time,time_day):
''' (number, str)--> number
This function converts a 12-hour time, represented by am/pm,to its equivalent 24-hour time.
Returns time in the 24-hour format.
'''
if time_day!='pm' and time_day!='am':
print('Input is not in the right format') #this is where input is not in the right format
return 0
else: print
return # write the rest of the program here
#Function 2:
def time_in_12h(time_24):
''' (number)--> (number,str)
This function converts a 24-hour time to the equivalent 12-hour time.
Returns time in the 12-hour format with am/pm.
'''
if 12< time_24 <24:
return (time_24)-12,'pm'
elif: # write the rest of the program here, I am lost :(
#Function 3: Main function where an Eastern time zone is the input
def time_zone(time,am_pm):
time_24=time_in_24h(time,am_pm)
time_in_24h(time,time_day)
This function converts a 12-hour time, represented by am/pm,to its equivalent 24-hour time. Returns time in the 24-hour format.
Let’s think about how this works by looking at examples:
“5 pm”: What is 5 pm in 24-hour format? “pm” means “post meridiem”, or “after noon”, so it’s the hours after noon. So the 24-hour format of “5 pm” is 17 hours, 5 + 12.
“9 am”: “am” means “ante meridiem”, or “before noon”, so it’s the hours before noon. So the 24-hour format of “9 am” is 9 hours.
Special case “12 am”: 12 am is midnight, so it’s 12 + 12 = 24, despite the “am”.
Special case “12 pm”: 12 pm is noon, so it’s just 12, despite the “pm”.
So, your code could look something like this:
if time == 12:
if time_day == 'am':
return …
else:
return …
elif time_day == 'pm':
return …
elif time_day == 'am':
return …
time_in_12h(time_24)
This function converts a 24-hour time to the equivalent 12-hour time. Returns time in the 12-hour format with am/pm.
This is the same as above, just in reverse. Just invert the logic applied above and you should simply be able to fill in the rest of your function. Especially since half of the job is already done in your code.
I am trying to identify the number of seconds that have elapsed given a time string. These time strings are not always consistent.
Examples:
'01:02' = 1 minute, 2 seconds = 62 seconds
'1-11:01:02' = 1 day, 11 hours, 1 minute, 2 seconds = 126062 seconds
I have tried time.strptime, but I didn't see a way to elegantly perform this operation. Any ideas?
One way to go about it is to gather all possible formats in an array and check the time_str against them:
time_formats = ["%m-%d:%H:%M","%H:%M"]
time_val = None
for fmt in time_formats:
try:
time_val = time.strptime(time_str,fmt)
except:
pass
if time_val is None:
print "No matching format found"
This try-catch structure is consistent with the EAFP principle in python. http://docs.python.org/2/glossary.html
I am a beginner programmer in Python and I have no idea how to proceed with the following question. There are a ton of similar questions out there, however there are none having to do with Python code.
I have tried to compare the strings but I am uncertain how to make the comparison. I'm pretty sure I need to take the first two numbers (hours) and divide by 12 if it is greater than 12 ... but that presents problems.
Question:
Time Conversion (24hrs to 12hr)
Write a function that will allow the
user to convert the 24 hour time format to the 12 hour format (with
'am','pm' attached). Example: from '1400' to '2:00pm'. All strings
passed in as a parameter will have the length of 4 and will only
contain numbers.
Examples (tests/calls):
>>> convertTime('0000')
'12:00am'
>>> convertTime('1337')
'1:37pm'
>>> convertTime('0429')
'4:29am'
>>> convertTime('2359')
'11:59pm'
>>> convertTime('1111')
'11:11am'
Any input or different methods would be awesome!
You could use the datetime module, but then you would have to deal with dates as well (you can insert wathever you want there). Probably easier to simply parse it.
Update: As #JonClements pointed out in the comments to the original question, it can be done with a one liner:
from datetime import datetime
def convertTime(s):
print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower()
You can split the input string in the hours and minutes parts in the following way:
hours = input[0:2]
minutes = input[2:4]
And then parse the values to obtain an integer:
hours = int(hours)
minutes = int(minutes)
Or, to do it in a more pythonic way:
hours, minutes = int(input[0:2]), int(input[2:4])
Then you have to decide if the time is in the morning (hours between 0 and 11) or in the afternoon (hours between 12 and 23). Also remember to treat the special case for hours==0:
if hours > 12:
afternoon = True
hours -= 12
else:
afternoon = False
if hours == 0:
# Special case
hours = 12
Now you got everything you need and what's left is to format and print the result:
print '{hours}:{minutes:02d}{postfix}'.format(
hours=hours,
minutes=minutes,
postfix='pm' if afternoon else 'am'
)
Wrap it up in a function, take some shortcuts, and you're left with the following result:
def convertTime(input):
h, m = int(input[0:2]), int(input[2:4])
postfix = 'am'
if h > 12:
postfix = 'pm'
h -= 12
print '{}:{:02d}{}'.format(h or 12, m, postfix)
convertTime('0000')
convertTime('1337')
convertTime('0429')
convertTime('2359')
convertTime('1111')
Results in:
12:00am
1:37pm
4:29am
11:59pm
11:11am
Some tips
int("2300") returns an integer 2300
2300 is PM.
time >= 1200 is PM
time between 0000 and 1200 is AM.
You could make a function that takes a string, evaluates it as integer, then checks if it is greater or less than the above conditions and returns a print.
import datetime
hour = datetime.datetime.now().strftime("%H")
minute = datetime.datetime.now().strftime("%M")
if int(hour) > 12:
hour = int(hour) - 12
amPm = 'PM'
else:
amPm = 'AM'
if int(hour) == 12:
amPm = 'PM'
if int(hour) == 0:
hour = 12
amPm = 'AM'
strTime = str(hour) + ":" + minute + " " + amPm
print(strTime)
Take hour and minute from datetime. Convert hour to an int. Check if int(hour) > 12. If so, change from AM to PM. Assign hour with int(hour) - 12. Check if hour is 0 for 12 AM exception. Check if hour is 12 for 12 PM exception. Convert hour back into a string. Print time.