Python help needed cant seem to solve this - python

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.

Related

An accurate stop watch using Python for logging minutes and hours worked. What's the best way to go about it? [duplicate]

This question already has answers here:
How to increase sleep/pause timing accuracy in python?
(4 answers)
Closed 5 months ago.
I've tried a few solutions from here with no luck. My Python timers are 10-30 seconds behind my smartphone stop watch after 10 minutes. I've tried the following:
def background3():
while True:
second = 0
minute = 0
hours = 0
while(True):
print('%d : %d : %d'%(hours,minute,second))
time.sleep(1)
second+=1
if(second == 60):
second = 0
minute+=1
if(minute == 60):
minute = 0
hour+=1;
and I also tried this:
def showCounter(self):
# Check the value of startWatch variable to start or stop the Stop Watch
if self.startWatch:
# Increment counter by 1
self.counter += 1
# Count and set the time counter value
cnt = int((self.counter/10 - int(self.counter/10))*10)
self.count = '0' + str(cnt)
# Set the second value
if int(self.counter/10) < 10 :
self.second = '0' + str(int(self.counter / 10))
else:
self.second = str(int(self.counter / 10))
# Set the minute value
if self.counter / 10 == 60.0 :
self.second == '00'
self.counter = 0
min = int(self.minute) + 1
if min < 10 :
self.minute = '0' + str(min)
else:
self.minute = str(min)
# Merge the mintue, second and count values
text = self.minute + ':' + self.second
# Display the stop watch values in the label
self.label.setText('<h1 style="color:white">' + text + '</h1>')
I'd like to be able to update a pyqt5 qlabel as time goes by every second, and I'd like to be able to display hours, minutes, and seconds in the qlabel. This has to be accurate as it is for work logging purposes. Eventually, I want to implement a qlabel that takes my overtime rate into consideration, and updates $ earned as time goes by. Does anybody have an example of what this may look like in pyqt5 using perhaps OS time ? Or is there some better way to do this?
EDIT:
This question is not a duplicate. The suggested articles were not helpful. I essentially need a way to count up from 0 using datetime. I tried replacing datetime.now but that did not work. The solutions suggested do not update my value in real time. They just take a stamp at the beginning, and subtract it from the end time. this is not what I am looking for. Does anybody know how I can watch seconds, minutes, and hours go by in real time through a pyqt5 qlabel?
def showCounter(self):
if self.startWatch:
text = str(datetime.now().strftime("%H:%M:%S"))
self.label.setText('<h1 style="color:white">' + str(text) + '</h1>')
Here's some code that prints every passing second without accumulating any lag. Just check the built-in clock at least once per second and update if the second has changed.
from datetime import datetime
import time
def time_to_str(time):
return str(time.hour) + ':' + str(time.minute) + ':' + str(time.second)
cur_time = datetime.now()
cur_str = time_to_str(cur_time)
while True:
time.sleep(0.2) # 200 ms, arbitrary
new_time = datetime.now()
new_str = time_to_str(new_time)
if new_str != cur_str:
print(new_str)
cur_str = new_str
The more often you check the time, the faster you can respond to the start of a new second. You'll never accrue lag regardless because you only print the time immediately after getting it from the system.
You should not expect a manufactured timer that relies on sleep() to be accurate for accrued time (stopwatch). Even if sleep() were 100% accurate, you are losing time outside of that in all of the function calls and other parts of the loop, which adds up over time (pun intended.)
The system time should be used. You can either use:
time.time()
or
datetime.now()
both have methods to peel out H:M:S.
As far as your "update loop"... well that is another story, you could use sleep there or whatever PyQt has to offer to refresh, but when you need to pull the time, do it as above.
If you want to use either as a "stopwatch" just capture the start time, do the subtraction. If you do this with datetime objects, the delta is a timedelta object that you can query. Do a little googling on timedelta and datetime.
Example:
In [1]: from datetime import datetime, timedelta
In [2]: tic = datetime.now()
In [3]: toc = datetime.now()
In [4]: td = toc - tic
In [5]: type(td)
Out[5]: datetime.timedelta
In [6]: td.seconds
Out[6]: 8

How to convert time written "h.mm" to decimal form with Python?

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.

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)

Sleep till next 15 minute hourly interval (00:00, 00:15, 00:30, 00:45)

I need my script to sleep till the next 15 minute hourly interval, e.g. on the hour, quarter past, half past, and quarter too.
It will look something like this
While True:
//do something
sleepy_time = //calculate time to next interval
time.sleep(sleepy_time)
You could write a series of if statements to check what the current minutes past the hour is then do ‘if current < 15’ and ‘if current < 30’ etc but that seems messy and inefficient.
EDIT: Building on #martineau's answer this is the code I went with.
import datetime, time
shouldRun = True
if datetime.datetime.now().minute not in {0, 15, 30, 45}:
shouldRun = False
# Synchronize with the next quarter hour.
while True:
if shouldRun == False:
current_time = datetime.datetime.now()
seconds = 60 - current_time.second
minutes = current_time.minute + 1
snooze = ((15 - minutes%15) * 60) + seconds
print('minutes:', minutes, 'seconds', seconds, ' sleep({}):'.format(snooze))
localtime = time.asctime( time.localtime(time.time()))
print("sleeping at " + localtime)
time.sleep(snooze) # Sleep until next quarter hour.
shouldRun = True
else:
localtime = time.asctime( time.localtime(time.time()))
print("STUFF HAPPENS AT " + localtime)
shouldRun = False
The difference between his answer and this is that this run the else block only once per interval then if the minute is still on the 0, 15, 30, 45 interval calculates the extra seconds to add to the minutes to sleep till the next interval.
You can achieve this using datetime...
A call to datetime.datetime.now() will return a datetime which you can get the current minute past the hour with .minute.
Once we have the number of minutes past the hour, we can do that modulo 15 to get the number of minutes to the next interval of 15.
From here, simply do a call to time.sleep() with that number of minutes times 60 (60 seconds in a minute).
The code for this may look something like:
import datetime, time
minutesToSleep = 15 - datetime.datetime.now().minute % 15
time.sleep(minutesToSleep * 60)
print("time is currently at an interval of 15!")
time.sleep(15*60 - time.time() % (15*60))
15*60 is a numer of seconds in every 15 mins.
time.time() % (15*60) would be the number of seconds passed in the current 15 min frame (since time 0 is 00:00 by definition). It grows from 0 at XX:00, XX:15, XX:30, XX:45, and up to 15*60-1 (actually, 15*60-0.(0)1 — depends on the precision of time measurements), and then starts to grow from 0 again.
15*60 - time.time() % (15*60) is the number of seconds left till the end of the 15-min frame. It, with a basic math, decreases from 15*60 to 0.
So, you need to sleep that many seconds.
However, keep in mind that sleep will not be very precise. It takes some time to process the internal instructions between time.time() is measured, and time.sleep() is actually called on the system level. Nano-fractions of a second, probably. But in most cases it is acceptable.
Also, keep in mind that time.sleep() does not always sleeps for how long it was asked to sleep. It can be waked up by signals sent to the process (e.g., SIGALRM, SIGUSR1, SIGUSR2, etc). So, besides sleeping, also check that the right time has been reached after time.sleep(), and sleep again if it was not.
I don't think #Joe Iddon's answer is quite right, although it's close. Try this (note I commented-out lines I didn't want running and added a for loop to test all possible values of minute):
import datetime, time
# Synchronize with the next quarter hour.
#minutes = datetime.datetime.now().minute
for minutes in range(0, 59):
if minutes not in {0, 15, 30, 45}:
snooze = 15 - minutes%15
print('minutes:', minutes, ' sleep({}):'.format(snooze * 60))
#time.sleep(snooze) # Sleep until next quarter hour.
else:
print('minutes:', minutes, ' no sleep')
import time
L = 15*60
while True:
#do something
#get current timestamp as an integer and round to the
#nearest larger or equal multiple of 15*60 seconds, i.e., 15 minutes
d = int(time.time())
m = d%L
sleepy_time = 0 if m == 0 else (L - m)
print(sleepy_time)
time.sleep(sleepy_time)
import schedule
import time
# Define a function named "job" to print a message
def job():
print("Job is running.")
# Set the interval for running the job function to 15 minutes
interval_minutes = 15
# Loop over the range of minutes with a step of interval_minutes
for minute in range(0, 60, interval_minutes):
# Format the time string to be in the format of "MM:SS"
time_string = f"{minute:02d}:00" if minute < 60 else "00:00"
# Schedule the job function to run at the specified time every hour
schedule.every().hour.at(time_string).do(job)
# Infinite loop to keep checking for any pending job
while True:
schedule.run_pending()
# Sleep for 1 second to avoid high CPU usage
time.sleep(1)

What is this exercise meaning in Thinkpython 2e?

The time module provides a function, also named time ,that return the current Greenwich Mean Time in "the epoch",which is an arbitrary time used as a reference
point.On UNIX systems, the epoch is 1 January 1970.
> import time
> time.time()
1437746094.5735958
write a script that reads the current time and converts it to a time of a day in hours, minutes, and seconds ,plus the number of days since the epoch.
I don't see how this exercise connect to the chapter 5.Conditionals and Recursion and how to write code to make this happen?
Thinks for answering my question.
So, as your advice, i wrote a section of code like this:
import time
secs = time.time()
def time():
mins = secs / 60
hours = mins / 60
days = hours/24
print 'The minues:',mins,'The hours:' ,hours, 'The days:',days
print 'The seconds:', secs, time()
It output the result like this:
The seconds:1481077157.6 The minues:24684619.2933 The hours:411410.321554 The days:17142.0967314 none, My question is where is "none" come from?
import time
def current_time():
current=time.time()
t_sec = current % 86400
c_hours = int(t_sec/3600)
t_minutes = int(t_sec/60)
c_mins = t_minutes % 60
c_sec = int(t_sec % 60)
days=int(current/86400)
print("The Current time is",c_hours,':',c_mins,':',c_sec)
print('Days since epoch:', days)
>import time
>epoch=time.time()
>#60*60*24=86400
>total_sec = epoch % 86400
>#60*60
>hours = int(total_sec/3600)
>total_minutes = int(total_sec/60)
>mins = total_minutes % 60
>sec = int(total_sec % 60)
>days=int(epoch/86400)
>print("The Current time is",hours,':',mins,':',sec)
>print("Days since epoch:", days)
EDIT in response to: "My question is where is "none" come from?"
In your print function at the end, you call 'time()', but you do not return anything, thus it prints 'None'.
If you want 'None' gone, try this:
import time
secs = time.time()
def time():
mins = secs / 60
hours = mins / 60
days = hours/24
print ('The minues:',mins,'The hours:' ,hours, 'The days:',days)
time()
print ('The seconds:', secs)
Though the point should probably be, that if you want to use a recursive function, you should return something that you then use to calculate with.
Let's have a look at the exercise description:
Write a script that reads the current time and converts it to a time of a day in hours, minutes, and seconds, plus the number of days since the epoch.
How I understand the question, is that the answer should be formatted something like this:
Today is 18 hours, 12 minutes, 11 seconds and 18404 days since epoch.
To get this answer, you could use a function using 'modulus operator', which is a part of paragraph 5.1. You could then subtract the variable containing 'today' with the number of days, then the hours, minutes and seconds. This is somewhat a recursive process, which could help your understanding for subsequent exercises.
import time
#the epoch time
epoch = int(time.time())
#calculate number of days since epoch
days = epoch / (60 * 60 * 24)
hour = days % int(days) * 24
min = hour % int(hour) * 60
sec = min % int(min) * 60
print(f"Days since epoch: {int(days)}\nCurrent Time: {int(hour)}:{int(min)}:{int(sec)}")

Categories