24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python - python

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.

Related

How can I process complex user input in python?

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)

making an input into a variable in python

I am very new to python and need some help, I am trying to make a simple if/else script.
my previous version worked as it should and I have have to make the only change of a user entering a variable rather than a pre-determined variable. But I get a syntax error on the final line, can anybody show me where I am going wrong.
my code is
hour = input('enter an hour')
if hour >= 0 and hour < 12:
clock = hour, 'pm' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)
thanks in advance for your help.
Multiple problems here:
In Python indentation (the spaces from a line or tabs if you wish) are important to distinguish different scopes of the code like functions, if statements etc. Your first line has such invalid indentation.
input('enter an hour') This function reads an input from the user and returns it as a string, regardless if you provide a numeric value. You need to use int() to convert it into an actual numeric value, so that you can then do range checks like "if is greater than 0 and less than 10" for example. Obviously, if you don't convert it to integer and you are working with strings you cannot do such range checks as the value is not treated as a numeric value.
Here is a working copy:
hour = int(input('Enter an hour: '))
if hour >= 0 and hour < 12:
clock = "{}am".format(hour)
elif hour >= 12 and hour < 23:
clock = "{}pm".format(hour)
else:
clock = 'That is not a time on the clock.'
print(clock)
There are 3 errors:
Your first line should not be indented.
Convert your input to numeric type, e.g. float or int.
Hours between 0 and 12 should be "am" rather than "pm".
This will work:
hour = float(input('enter an hour'))
if hour >= 0 and hour < 12:
clock = hour, 'am' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)
The error is IndentationError: unexpected indent This means you write the line of code indented. that's incorrect. To solve it remove the spaces before first line.
You also have to specify the type of input.
hour = int(input('enter an hour'))

Python help needed cant seem to solve this

I'm suppose to write a code to give me the output of a value between 0 and 86400 and the current time in the 24 hour clock. However I am getting stuck when it comes to writing the formulas for the 24 hour clock and the print function. Here's the code I have written so far.
total_time = float('70000')
hours = int(total_time / 3600.0)
minutes = int((total_time - (hours * 3600.0)) / 60.0)
seconds = int(((total_time) - (hours * 3600) - (minutes * 60)))
print("Enter a value between 0 and 86400", total_time) print("The current time is",hours.minutes.seconds)
Firstly, get the current hour, minute and seconds:
import datetime
now = datetime.datetime.now()
# The current time:
hour = now.hour
minute = now.minute
second = now.second
Then simply output it:
print("Current time: {}:{}:{}".format(hour,minute,second))
It seems to me you are asking the user to enter a number between 0 and 86400 and then you want to translate that to hh:mm:ss format. But your code is not getting any input from the user, and the last line of the code has syntax errors.
To get you started, you need to fix your print() calls at the end. Put one statement to a line, and use commas not fullstops:
print("Enter a value between 0 and 86400", total_time)
print("The current time is",hours,minutes,seconds)
That will give you the output:
Enter a value between 0 and 86400 70000.0
The current time is 19 26 40
Which is correct, in the sense that an offset of 70,000 seconds from 0h00 today is 19h26m40s.
If you want to get actual user input, then you need to ask for it, at the top of your program, before you do the calculations, in an input() call:
total_time=float(input("Enter a value between 0 and 86400: "))
If you want pretty formatting of the answer then do
print(f"The current time is {hours:02d}:{minutes:02d}:{seconds:02d}")
None of this relates to finding the current time, which Suraj Kothari's answer addresses.

Convert a string like "1 hour and 22.5 seconds" into seconds to make calculations

I am using python, and would like to read a log file that contain info about time.
The string is like this: "1 hour and 22.5 seconds". or "41 seconds" or "22.3 seconds"; Not sure exactly what would be the best way to handle this case. I do not have control on how the data is written, I can just process it.
I was thinking to read the string; then separate it in single strings; so if I find "hour" at position [2] in the string list, I add 3600 seconds in an int variable; if I find minutes then I get the value and check if it has decimals or not, and parse it as such; adding it to the hours if present.
Is this something reasonable or there is a better way? Kinda prone to error to base your conversion on positions that may not be the same for different strings.
Using regular expressions:
UNIT2SECONDS = {
'hour': 3600,
'minute': 60,
'second': 1,
}
text = "4 hours, 43 minutes and 3 seconds"
seconds = sum(sum(map(float, re.findall("([.0-9]+)\s+%s" % k))) * v for k, v in UNIT2SECONDS.items())
Without regex, you can do something like this:
times = ['1 hour and 22.5 seconds', '3 hours 4 minutes and 15 seconds', '22.3 seconds', '6 hours']
# attempt to normalize the input data
times = [t.lower().replace('and','').replace('hours','hour').replace('minutes','minute').replace('seconds','second').replace(' ',' ') for t in times]
secondsList = map(getseconds, times)
def getseconds(sTime):
seconds = 0.0
S = sTime.split()
if 'hour' in S:
seconds += (3600 * float(S[S.index('hour')-1]))
if 'minute' in S:
seconds += (60 * float(S[S.index('minute')-1]))
if 'second' in S:
seconds += float(S[S.index('second')-1])
return seconds
I think your idea is not bad. I would use regex to find the occurences of hours, minutes and seconds and use grouping to get the corresponding number. As an example for the case of hours, consider this:
hours = re.match(r'(\d{1,2})(\shour[s]?)', "1 hour and 50 minutes")
if hours:
seconds = hours.group(1) * 60 * 60
The brackets () allow for grouping, which allow you to easily extract the number. You can perform the same for minutes and seconds. If the regex does not return anything, hours will be None, thus you can easily check for if hours: and then perform your math on the converted string.

Knowing if time has already passed or not python

Im using this code right now to get the difference of two different times
from time import strftime
from datetime import datetime
fmt = '%H:%M'
currentTimeString = strftime(fmt) #get the current time
gameTimeObject = datetime.strptime(time , fmt)
currentTimeObject = datetime.strptime(currentTimeString, fmt)
diff = currentTimeObject-gameTimeObject
diff_minutes = diff.seconds/60
I have a for loop that loops through different time values, 11:00, 12:00, 13:00, 14:00.
For the purpose of this example lets say the currentTime is 13:23
Im getting the result that i want when the time has passed meaning, 11:00, 12:00, 13:00 but when it comes to 14:00 the diff_minutes shows the value 1403
Why this is a problem is because I'm doing this after that code is executed
if diff_minutes >= 0 and diff_minutes <= 47:
time = str(diff_minutes)
elif diff_minutes >= 48 and diff_minutes <= 58:
time = "HT"
elif diff_minutes >= 59 and diff_minutes <= 103:
time = str(diff_minutes)
elif diff_minutes >= 104 and diff_minutes <= 107:
time = "90'"
elif diff_minutes >= 108: # HERE IS THE PROBLEM <<<<<<-------
time = "FT"
As you can see the times that has not yet been passed will change to "FT" since I'm using that if statement to know if the time of a games is over. How can i fix this?
--- EDIT more information of what I'm trying to do as asked
So what I'm trying to do here is to set the time variable to a soccer game. The different times as mentioned above 13:00 etc are the times of which when the game starts. So what i want to do is if the currentTime is 13:23, then i would change the time label of that soccer game to 23' since 23minutes has passed. If the total time that has passed is over 108 minutes then it means the game is over that is why i set the time variable to "FT" in the last if statement.
As i said before this is where the problem occurs since the diff_minutes gives me a value of higher than 108 minutes when the games has not yet been started it will change the time variable to "FT" which is wrong
So what we really should do is work only with datetime objects here. When you do math on them, the produce timedelta objects. These timedelta objects are comparable. This makes writing your code secretarial. Also - since an if/elif/else tree is short circuiting, you need not check if a time is between two times, just less than the upper bound. I admit my domain knowledge of soccer is limited to knowing it is a 90 minute game, so you may need to adjust this, but it should give you the idea.
import datetime
def gametime(hour, minute):
now = datetime.datetime.now()
starttime = datetime.datetime.combine(datetime.date.today(), datetime.time(hour, minute))
dif = now - starttime
if dif < datetime.timedelta(seconds=48*60):
return dif.seconds / 60
elif dif < datetime.timedelta(seconds=58*60):
return "Half Time"
elif dif < datetime.timedelta(seconds=104*60):
return dif.seconds / 60
elif dif < datetime.timedelta(seconds=108*60):
return "90'"
else:
return "Final"
PS: Seriously, Guido?
PPS: I should have tested this before posting it. I am sorry that I did not.

Categories