I am trying to print the current time before my normal prints
global begtime
begtime = str(datetime.datetime.now()).split('.')[0]
global secondtime
secondtime = begtime.split(' ')[1]
global time
time = '[' + secondtime + ']' + ':'
print time
datetime.datetime.now returns in the format of :
year.month.date hour.minute.second
so I first split at the '.' to get the individual times, then I split at the space to get just the time.
then I formatted it as [hour:min:sec]
It works, but the time is not correct, it will print same time for all prints even if they happen minutes apart.
I want the exact time for every print.
For your code, you're probably setting the time earlier in your program and then accessing it later thinking it is generating a new time. It won't generate a new time every time you print it. It will only generate a new time every time you run begtime = str(datetime.datetime.now()).split('.')[0]
The better way to do this would be to use Date.strftime(format). I've included an example of this below.
import datetime
import time
now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))
time.sleep(10)
now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))
This will print the current time and then 10 seconds after the current time after 10 seconds.
Related
Im using datetime with pytz, but i cant get time to update.
format = "[%B %d %H:%M]"
now_utc = datetime.now(timezone('UTC'))
greece = now_utc.astimezone(timezone('Europe/Athens'))
date = greece.strftime(format)
For example i print(date) at 11:30, it stays like that.
Any idea?
As it is, date remains the same throughout the runtime. There is nothing to update it at the current time. If you want to check and print the time at regular intervals, you need to define a function and have your script call it after that amount of time.
import time
fmt = "[%B %d %H:%M]"
def print_now()
now_utc = datetime.now(timezone('UTC'))
greece = now_utc.astimezone(timezone('Europe/Athens'))
date = greece.strftime(fmt)
print(date)
while True:
print_now()
time.sleep(60) # argument is time to wait in seconds
As long as True is True (which is always), the loop will continue, unless you define some condition to force it to end at some point. Of course, you could have the print_now() function contents within the while loop, but it's a bit cleaner to have it in it's own function.
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.
Goal: I would like to see how many times python is able to print something per 1 second.
For educational purposes I'm trying to make a script that shows how many times per every second a random module will appear in a loop. How to do it in a fastest pythonic way?
At first, to count seconds I wrote this code:
import time
sec = 0
while True:
print(sec)
time.sleep(1)
sec += 1
But this one seems slower than a real seconds.
So I decided to use local seconds. Also, before continue my script I wanted to count how many times python will print 'you fool' manually, so I wrote following code:
import time
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
while True:
print(LocalSeconds(), 'you fool')
Output:
first second - 14 times per second;
next second - 13 times;
next second - 12 times, etc. Why it goes slower?
Where I end / stuck right now:
import time, random
def RandomNumbers():
return random.randint(3,100)
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
def LocalSecondsWithPing():
local_seconds_ping = time.gmtime()[5:-3]
local_seconds_ping = int(local_seconds[0:1])
return local_seconds_ping
record_seconds = []
record_seconds_with_ping = []
while True:
record_seconds.append(LocalSeconds())
record_seconds_with_ping.append(LocalSecondsWithPing())
if record_seconds == record_seconds_with_ping:
RandomNumbers()
del record_seconds_with_ping[0]
del record_seconds[-1]
Also, I guess I need to use "for" loop, not "while"? How to do this script?
Counting a single second won't give you a good result. The number of prints in a single second may vary depending on things like other threads currently running on your system (for the OS or other programs) and may be influenced by other unknown factor.
Consider the followind code:
import calendar
import time
NumOfSeconds=100 #Number of seconds we average over
msg='Display this message' #Message to be displayed
count=0 #Number of time message will end up being displayed
#Time since the epoch in seconds + time of seconds in which we count
EndTime=calendar.timegm(time.gmtime()) + NumOfSeconds
while calendar.timegm(time.gmtime())<EndTime: #While we are not at the end point yet
print(msg) #Print message
count=count+1 #Count message printed
print(float(count)/NumOfSeconds) #Average number of prints per second
Here calendar.timegm(time.gmtime()) gives us the time in seconds since the epoch (if you don't know what that is, read this. But basically it's just a fixed point in time most computer system now days use as a reference point.
So we set the EndTime to that point + the number of seconds we want to average over. Then, in a loop, we print the message we want to test and count the number of times we do that, between every iteration checking that we are not past the end time.
Finally we print the average number of times per seconds that we printed the message. This helps with the fact that we may end up start counting near the end of a whole second since the epoch, in which case we won't actually have a whole second to print messages, but just a fraction of that. If we make sure NumOfSeconds is large enough, that error addition will be small (for example, for NumOfSeconds=100 that error is ~1%).
We should note that the actual number would also depend on the fact that we are constantly testing the current time and counting the number of prints, however, while I haven't tested that here, it is usually the case that printing to the screen takes significantly longer time than those operations.
I have defined a function record which appends value to a list named as lists for a duration of Time.Whenever I call this function for the first time it appends 19 values to lists,but when I call it second time it appends 20 values to lists even though the time parameter that I was using both the times was 1 sec.Is there any way that I could get same no of values get appended to a list when I call the function multiple times?
import time
lists=[]
first_list=[]
second_list=[]
def record(lists,Time):
start_time=time.time()
print "start_time",start_time
print "time.time",time.time()
while(time.time()-start_time)<=Time:
lists.append(1)
print "list",lists
print "length of list after appending",len(lists)
record(first_list,0.05)#first time
print 1
time.sleep(5)
record(second_list,0.05) #second time
The time it takes to do something is not fixed. It takes as long as it takes. But you need both to be the same, so just make them the same by checking both. This code does the desired amount of work, and then calls time.sleep() until the remaining time block runs out. That's way better than looping and checking time() repeatedly, because looping and checking time makes the cpu work hard to do nothing. time.sleep is specifically there to avoid using the cpu.
import time
def record(mylist, duration, count):
start_time=time.time()
while len(mylist) < count:
mylist.append(1)
remaining_time = time.time() - start_time;
time.sleep(duration - remaining_time)
print "calling first pass"
start_time=time.time()
l1 = []
record(l1, 5, 100) #second time
actual_duration = time.time() - start_time
print "length is", len(l1), "actual time was", actual_duration
print "calling second pass"
start_time=time.time()
l2 = []
record(l2, 5, 100) #second time
actual_duration = time.time() - start_time
print "length is", len(l2), "actual time was", actual_duration
Obviously, if you try to do more than you can in the specified time, you won't. Maybe you can return an error if that happens? If you check time() during the function you can exit early, but I would not recommend checking it too often.
the number of times the list gets appended is almost arbitrary, the exact time it takes to execute is mostly affected by what happens to be running on your computer at the time. For example if you opened your internet browser during the second call that could slow down the exact execution time.
On my machine both calls on average only appended 4 values each call, but sometimes was 5.
Is there any way that I could get same no of values get appended to a
list when I call the function multiple times?
Yes: do not base the number of items appended on the time it takes to execute, instead base it on the number of times you want to append:
def record(list_to_append_to, times_to_append):
for _ in range(times_to_append):
list_to_append_to.append(1)
or similarly you could use .extend:
def record(list_to_extend, extend_length):
list_to_extend.extend(1 for _ in range(extend_length)
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.