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.
Related
I have a python code,
def test():
print("Test")
I want to run this code exactly at 09:00:00 am and loop it to run it after each 60 seconds till 16:00:00 pm.
How can I achieve it?
A partial answer (EDIT: look at the first comment under this answer for improvements which can be made):
This can be done using only Python, if you import the Tkinter and datetime modules. I wouldn't recommend running this particular program for as long as in your question, but it does work as a proof of concept.
# Runs:
# Starting at the specified start time,
# Every specified interval (in seconds) until the specified end time,
# With precision equal to precisionInterval (i.e. how often does the function check what time it is)
# The first two parameters are strings of the form 'hh:mm:ss'
# The third parameter is an integer representing seconds
# The fourth parameter is an integer representing milliseconds
# The last parameter should not be provided by the user.
import tkinter as tk
import datetime
window = tk.Tk()
def timerFunction(fromStartTime, untilEndTime, repeatEveryThisManySeconds, precisionInterval, untilNextTime=0):
functionParameters = [fromStartTime, untilEndTime, repeatEveryThisManySeconds, precisionInterval, untilNextTime]
# The first 11 characters of datetime.datetime.now() are the year, month and day,
# separated by hyphens and followed by a space. Remove these characters as they are not relevant.
# The next 8 characters are the hour, minute and second, separated by colons. After this are a
# decimal point and milliseconds. Remove these final characters too.
currentTime = str(datetime.datetime.now())[11:19]
# First, check whether it is the start time yet. If it is at or after the start time, start
# printing output. Because of the way the time is formatted, strings can be compared directly
# without converting to numbers first.
if (currentTime >= fromStartTime):
if (untilNextTime <= 0):
# Reset the countdown every time output is printed
print("Test: it is now " + currentTime)
functionParameters[4] = repeatEveryThisManySeconds*1000
else:
functionParameters[4] -= precisionInterval
if (currentTime >= untilEndTime):
# Avoid useless looping after the deadline
return
window.after(precisionInterval, lambda: timerFunction(*functionParameters))
timerFunction('15:45:00', '15:50:00', 1, 100)
For some reason, it occasionally skips a second, and I don't know why this would be since the update rate is set to 0.1 seconds.
I am trying to understand how to make a string based on the current time, and time ranges in Python. So, if it's between 8am and 11am, for Python to identofy what time it is, and automatically return a "breakfast" string; and if its between 11am to 4pm --> return a lunch string
First of all, please, try to be clear when asking and bring some examples that you tried before.
Getting the time is easy as:
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
You can see more information about datetime module here
So, current_time brings a string with the time. To select minutes or hours you need to pick up the position that they're at.
For example:
myTime = "12:34:56"
seconds = myTime[-2:]
print(seconds)
56
For more examples on slicing strings, here
You want integers instead of strings?
seconds = int(seconds)
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 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
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.