Get the time in seconds in this form d.ddd - python

I want to get the elapsed time in the form of seconds in this form d.ddddddd, e.g., 5.656 seconds. When using time.time(), the value becomes very large, something like 1485831617.19 which has 10 values. How can modify the following way:
start = time.time()
time.sleep(2)
elapsed = time.time()
pretty = '{:.3f}'.format(elapsed)
print pretty
This still print something like 1485832865.471. Thank you for help in advance.

Try something like this:
pretty = "%.3f" % (elapsed)

Related

python3 why does my comparison change the formatting?

I have 1 time that is formatted like this
start_time 01:13:05
I have a second time that looks like it
Current time 01:13:10
When I calculating the difference, it produces the correct answer but chops a zero off
code:
new_start_time = datetime.strptime(start_time, '%H:%M:%S')
new_current_time = datetime.strptime(str(current_time), '%H:%M:%S')
elapsed_time = new_current_time - new_start_time
produces:
elapsed time 0:00:10
The 10 is correct but what happened to the zero? How do I hack it back on? I need it.
Add:
elapsed_split = str(elapsed_time).split(":")
elapsed_time = int(elapsed_split[0]).zfill(2) + elapsed_split[1:]

How to get the output for all the values from the given time values?

import datetime
data = {'13:55':0,'13:56':1,'13:57':2, '13:58':3}
while True:
timee = datetime.datetime.now()
time = timee.strftime("%H:%M")
while time not in data:
timee = datetime.datetime.now()
time = timee.strftime("%H:%M")
if time in data:
print('Done')
print(data[time])
From the given code, I always get an output in case of the first or the last object in the dictionary, for example, if the current time is 13:55, I want it to display the output 'done', similarly if the time is 13:56, I want the same output and so on. Also, I don't want to break the loop since I want my program to run continuously. But it only gives me an output in case of 13:55 or 13:58 or it wouldn't even give me an output.
Whereas what I want is basically, I want it to give me an output every time the time is present in the dictionary. Please help me.
(I'm really sorry if you don't get it, I've tried my best to put this forward).
If any questions please let me know.
Thank you in advance.
an illustration of my comment; at the moment, both your while loops do the same thing; you can simplify to
import datetime
import time
data = {'13:51':0,'13:52':1,'13:53':2, '13:54':3,
'found':[]}
while True:
t = datetime.datetime.now().strftime("%H:%M")
if (t in data) & (t not in data['found']):
print(f'Done, found time {t} in data\n value: {data[t]}')
data['found'].append(t)
time.sleep(1)
I've added a little helper key to track which times were found.

wait function that uses while

I just wrote a function that looked like this:
def block_for(seconds):
"""Wait at least seconds, this function should not be affected by the computer sleeping."""
end_time = datetime.datetime.now() + datetime.timedelta(seconds)
while datetime.datetime.now() < end_time:
pass
Can anything bad come of this? Should there ideally be something inside the while loop?
time.sleep(seconds) seconds does just that without burning through CPU cycles. your loop keeps the CPU fully busy. i do not know for you but i consider this bad.
maybe putting time.sleep(1) in the while loop will require less cycles? Or
def block_for(seconds):
"""Wait at least seconds, this function should not be affected by the computer sleeping."""
end_time = datetime.datetime.now() + datetime.timedelta(seconds=seconds)
while datetime.datetime.now() < end_time - datetime.timedelta(seconds=1):
time.sleep(1)
while datetime.datetime.now() < end_time:
pass

Python - Print index of for loop only once every five minutes

I'm trying to get a for loop to print the value of 'i' every 5 minutes
import threading
def f(i):
print(i)
threading.Timer(600, f).start()
for i in range(1,1000000000000):
f(i=i)
However, this method results in the code printing the value of i instantly since it calls 'f' as soon as it finds 'i'.
I know this is not the first time someone will ask, nor the last, but I can't get it to work on a for loop nested within a function.
I'm fairly new to Python and I'd appreciate any help.
How about just keeping track of how long has passed in the loop?
from timeit import default_timer as timer
start = timer()
freq = 5 * 60 # Time in seconds
last_time = 0.0
for i in range(int(1e8)):
ctime = timer()
if ctime - last_time > freq:
print(i)
last_time = ctime
I imagine you can make this more efficient by only checking the time every N iterations rather than every time. You may also want to look into using progressbar2 for a ready-made solution.
I prefer using datetime, as I think it's more intuitive and looks a bit cleaner. Otherwise, using more or less the same approach as Paul:
from datetime import datetime, timedelta
print_interval = timedelta(minutes=5)
# Initialize the next print time. Using now() will print the first
# iteration and then every interval. To avoid printing the first
# time, just add print_interval here (i.e. uncomment).
next_print = datetime.now() # + print_interval
for i in range(int(1e8)):
now = datetime.now()
if now >= next_print:
next_print = now + print_interval
print(i)
Also note that before python 3.x xrange would be preferable over range.

While loop, have two if i in statements

OK so two questions here.
First,I am trying to show start time. I am doing this with program_time. Second, I also want to show elapsed time. I would also like to show this in microseconds.
import time
a= time.time()
print a
while True:
program_time= time.time()
elapsed=program_time - a
for i in [program_time]:
print "%s\r" % i,
Thanks in advance.
Your code looks almost correct. This should show the start time, and each subsequent program time as the while loop proceeds (albeit very quickly). Perhaps you need to perform some calculation in the loop?
import time
a = time.time()
print "Starting time is %s" % str(a)
while True:
# Clear the screen each iteration to "recycle" the lines
print chr(27) + "[2J"
program_time = time.time();
elapsed = int(round((program_time - a) * 1000)) * 100
print "Start time is %s" % a
print "Elapsed time is %s" % elapsed
# Simulate some work
time.sleep(1)
Assuming your question is "why does my program output the current time instead of the elapsed time," the answer is "because program_time is being printed rather than elapsed."

Categories

Resources