I am creating a digital to analogue converter. I have a variable storing the user's input, which should be a digital time (e.g 13:00). I then doing inputVariable%12 to get the time as it would be on an analogue clock (e.g 1). However, to do this I need to delete any extra information the user has given (e.g :00) so I only have stored the number. How do I do this?
time = input("Enter digital time here:\ne.g 12:00\n")
#Delete extra information here
time = int(time)
time = time%12
time = str(time)
print(time + " o'clock")
I assume that there would be no errors in your input (e.g. user entering some other character, hours above 23, etc.). Considering your input format you should first split on :. This should give you two parts: hours and minutes. After this you can process as you want:
time = input("Enter digital time here:\ne.g 12:00\n")
hours, minutes = time.split(':')
hours = int(hours)
hours = hours % 12
hours = str(hours)
print(hours + " o'clock")
Related
I am writing a program to track my working hours as a chef. I'm looking for it to ask when I started, finished and how long a break I had that day. The problem I am running into is I keep getting a value error on line 12 (time data '1900-01-01 10:00:00' does not match format '%H:%M') and I'm having trouble applying the threads on here that try to explain the solution to my own problem. I know what I need to do is extract some of the data from the datetime object as a whole but so far everything I have tried has thrown up an error.
Code below;
from datetime import datetime
fmt = "%H:%M" # The time format i.e hours and minutes
print("Please input your starting and finishing times for the following days.")
print("Wednesday:") # Denotes which day is being asked about
wed_start_in = (input("What time did you start?")) # asks starting time
wed_start = str(datetime.strptime(wed_start_in, "%H:%M")) # converts time start input into a datetime object
wed_finish_in = (input("And what time did you finish?")) # asks finishing time
wed_finish = str(datetime.strptime(wed_start_in, "%H:%M"))
wed_hours = datetime.strptime(wed_start, fmt) - datetime.strptime(wed_finish, fmt)
print(wed_hours)
You're converting back and forth into strings; instead, parse each of the times once, then keep them as times. Only convert them back to strings (if necessary) at the very end.
wed_start_in = input("What time did you start?") # asks starting time
wed_start = datetime.strptime(wed_start_in, "%H:%M") # converts time start input into a datetime object
wed_finish_in = input("And what time did you finish?") # asks finishing time
wed_finish = datetime.strptime(wed_finish_in, "%H:%M")
wed_hours = wed_finish - wed_start
print(wed_hours)
I have a string that looks like this
time = "2020-04-15 21:27"
That's based on normal time zone +0
how can i add hours to the string so it become like this
for example let's add 5 hours to the time
the time string will become like this
time = "2020-04-15 02:27"
then the day should be updated
so the final result will look like this
time = "2020-04-15 02:27"
how can i do that ?
Edit:
i also need to change the day because 24 hours have passed
It is unclear if you mean creating your own clock or just updating a string every hour.
Option one:
import time
While True:
t = time.ctime(%h)
print(t)
#the above produces a live clock only showing hours.
#you could add %s for seconds separated by commas and thd like.
Option 2:
import time
T = #whatever you want it to be
time.sleep(300)
T = the prev num bit you want to change + 5
Hope this helps!
Happy coding
I prompt the user to input what time they start and finish their job. Then I need to calculate what they will earn (given a 97 currency/hour salary). The answer should also not have any decimals (so it should be rounded off). I can't seem to get it to work though.
As shown below, I tried taking the difference between the two inputs from the user and then splitting them to hours and minutes. After that just doing the calculations.
difference = round(float(finishing_time)-float(start_time), 2)
hours, minutes = str(difference).split(".")
salary_hours = int(hours)*97
salary_minutes = int(minutes)//60*97
salary = salary_hours + salary_minutes
So if start_time = 8.30 and finishing_time = 11.15 the salary should be 267, but I get 291 currency.
A couple of things to be careful of, is the rounding off that occurs at every level, which also occurs when you do math by hand and pencil! There is a reason why when you perform calculations one typically does the rounding off when the entire calculation has been performed otherwise one would come up with a vastly different answer as you pointed out.
I'd tackle this perhaps by doing something like this
from datetime import datetime
# quick way to generate a datetime object with start time would be like
start_time = datetime.now()
# replace the hours and minutes you want in your case its
start_time = start_time.replace(hour=8, minute=30)
end_time = start_time.replace(hour=11, minute=15)
# calling replace returns a new distinct datetime object
def calculate_salary(start_time, finish_time, pay_rate):
# will be in seconds
delta_seconds = finish_time - start_time
# convert to hours
hours_worked = (delta_seconds.seconds) / 3600
# calculate pay
pay = hours_worked * pay_rate
return pay
In this case calling the function gives a value of
In [1]: calculate_salary(start_time, end_time, 97)
Out[1]: 266.75
While i dont advocate doing calculations on time without a time module. I assume you know what your doing and that your calculations are simple I.E they wont rolle over midnight and the finish time will always be greater than the start time and finish on the same day. With that in mind the following code should produce your result without using a datetime module. However like #william bright answer, a datetime module would be my prefernce for code like this.
def get_hours(time_string):
time_split = time_string.split(".")
whole_hours = int(time_split[0])
fraction_hours = int(time_split[1]) / 60
return whole_hours + fraction_hours
start_time=input("start time: ")
finish_time=input("finish_time: ")
total_hours = get_hours(finish_time)-get_hours(start_time)
salary = total_hours*97
print(round(salary))
OUTPUT
start time: 8.30
finish_time: 11.15
267
So, my bad for perhaps being unclear in my statement, but since this is a work in progress for the next couple weeks/months, what I came up with was the following:
starting_time = input("At what time did you start working? ")
finishing_time = input("At what time did you finish working? ")
hours1, minutes1 = starting_time.split(".")
hours2, minutes2 = finishing_time.split(".")
minutes1 = float(minutes1)/60
starting_time_new = float(hours1)+minutes1
minutes2 = float(minutes2)/60
finishing_time_new = float(hours2)+minutes2
salary = round((finishing_time_new-starting_time_new)*97)
print("Started working at:",b)
print("Stopped working at:",s)
print("Your salary is",salary,"currency.")
The solution from where I started was to just focus on changing the minutes to the correct decimals instead of focusing on the hours too.
I am well aware that it is far from perfect, in fact, it is probably really bad. However, I am new to programming in Python and taking a course to be better.
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'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.