Print Only Seconds for perf_counter() - python

My code is this:
import time
import winsound
frequency = 2500
duration = 1000
while time.perf_counter() < 5:
print(time.perf_counter())
winsound.Beep(frequency, duration)
How do we only print the seconds?

A naive approach, replace your while loop with:
sec = 0
while time.perf_counter() < 5:
now = max(round(time.perf_counter()), sec)
if now > sec:
sec = now
print(sec)

Related

Number of 15 minutes intervals between two datetimes

from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
How can I find the number of 15 minutes intervals exist between start and finish?
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start
number_of_intervals = elapsed / timedelta(minutes=15)
elapsed is the timedelta between start and finish. Divide by 15 minutes to calculate how many 15 minute intervals fit in there.
Note that this returns a float, so includes fractional intervals. Round as appropriate.
You need to find the difference between start and finish in minutes, divide by 15, and make that an int:
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
difference = (finish - start).total_seconds()/60
quarters = int(difference/15)
i would write something similar to this:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
date_times = [from_date_time.strftime(DATE_TIME_STRING_FORMAT)]
date_time = from_date_time
while date_time < to_date_time:
date_time += timedelta(minutes=15)
date_times.append(date_time.strftime(DATE_TIME_STRING_FORMAT))
print(date_times)
Output:
['2016-06-06T05:00:00.000000Z', '2016-06-06T05:15:00.000000Z', '2016-06-06T05:30:00.000000Z', '2016-06-06T05:45:00.000000Z', '2016-06-06T06:00:00.000000Z']
Edit:
If you are interested in just the number of 15 minute intervals you can use something like:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
print((to_date_time-from_date_time) / timedelta(minutes=15))
You can use time library instead of date time. time works with seconds and you should convert minutes to seconds:
import time
interval = 45*60
start = time.time()
finish = time.time() + interval
diff = finish - start
print(diff // (15*60))
Simply compare start and finish like so:
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start # This is a timedelta object
reference_interval = 15*60 # interval in seconds
number_of_intervals = elapsed.seconds/reference_interval
As pointed out by Sören, this will not work if 'elapsed' is more than one day, in which case, simply compute the number as follow:
number_of_intervals = (elapsed.days*86400+elapsed.seconds)/reference_interval
# (86400 seconds in a day)

How to make a count for each day passed from start date in python

I'm looking for a way to count each day passed from a start date in python. So if the start date was 21/02/2020 and count equals to 0, when the next day starts count should increment by 1.
Edit: After using Rusty's code I am able to show you a minimal reproducible example.
import datetime
start = datetime.datetime.strptime(input("Choose a start date (mm/dd/yyyy): "), '%m/%d/%Y')
current = datetime.datetime.now()
delta = current - start
count = delta.days
print(count)
import datetime
import time
count = 0
# "...from today..."
today = datetime.datetime.today()
# "...to infinity..."
while True:
now = datetime.datetime.today()
# "...as soon as the next day starts..."
if today.day != now.day:
# "...it would increment count by 1..."
count = count + 1
print(count)
today = now
time.sleep(1)
import datetime
today = datetime.datetime.strptime('03/21/2020', '%m/%d/%Y')
tomorrow = datetime.datetime.strptime('03/22/2020', '%m/%d/%Y')
next_saturday = datetime.datetime.strptime('03/28/2020', '%m/%d/%Y')
delta = tomorrow - today
count = delta.days
print(count)
delta = next_saturday - today
count = delta.days
print(count)

Datetime format when adding time durations

time_1 = datetime.timedelta(hours = hours_1, minutes = minutes_1, seconds = seconds_1)
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
when added it gives the answer in days and hours but I really just want the total number of hours.
This should help.
import datetime
time_1 = datetime.timedelta(hours = 10, minutes = 2, seconds = 5)
time_2 = datetime.timedelta(hours = 30, minutes = 5, seconds = 7)
print(time_1 + time_2)
print(((time_1 + time_2).total_seconds()/60)/60)
Output:
1 day, 16:07:12
40.12

Round time in python odoo

I use below example for round time in odoo.
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, "%Y-%m-%d %H:%M:%S")
time2 = datetime.strptime(rec.finish, "%Y-%m-%d %H:%M:%S")
rec.total_time = round(((time2 - time1).seconds / float(60*60) - self.pause))
For example:
if start = 07:57:21 , finish = 16:25:36, pause = 1 get result 7 hours
if start = 07:57:34 , finish = 16:28:42, pause = 1 get result 8 hours
First and second time different is 3 minutes but in result that is one hours!
How change round if total time >= 7 hours 30 minutes 01 second I need result 8 in other solution 7.5 (7 hours and 30 minutes)
For "%Y-%m-%d %H:%M:%S" you can use DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
For your problem you can use round(x, n). Example:
round(7.4, 0) = 7
round(7.5, 0) = 8
round(7.5, 1) = 7.5
Here you need n = 1 for 7.5 and n=0 for the 'standard' round. You can check 7.5 with ((7.5 - 0.5) % 1) == 0 and convert it from boolean to int directly with int()
The general solution is:
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
total_time = (time2 - time1).seconds / float(60*60) - self.pause
rec.total_time = round(total_time, int(((total_time - 0.5) % 1) == 0))
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
total_time = (time2 - time1).seconds / float(60*60) - self.pause
total_time = 2*total_time
if 2*total_time%1 <=0.5 :
res = round(total_time)
else :
res = round(2*total_time)
rec.total_time = res

Get upload/download kbps speed

I'm using the library called psutil to get system/network stats, but I can only get the total uploaded/downloaded bytes on my script.
What would be the way to natively get the network speed using Python?
If you need to know the transfer rate immediately, you should create a thread that does the calculations continuously. I'm not an expert on the subject, but I tried writing a simple program that does what you need:
import threading
import time
from collections import deque
import psutil
def calc_ul_dl(rate, dt=3, interface="WiFi"):
t0 = time.time()
counter = psutil.net_io_counters(pernic=True)[interface]
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
counter = psutil.net_io_counters(pernic=True)[interface]
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last in zip(tot, last_tot)
]
rate.append((ul, dl))
t0 = time.time()
def print_rate(rate):
try:
print("UL: {0:.0f} kB/s / DL: {1:.0f} kB/s".format(*rate[-1]))
except IndexError:
"UL: - kB/s/ DL: - kB/s"
# Create the ul/dl thread and a deque of length 1 to hold the ul/dl- values
transfer_rate = deque(maxlen=1)
t = threading.Thread(target=calc_ul_dl, args=(transfer_rate,))
# The program will exit if there are only daemonic threads left.
t.daemon = True
t.start()
# The rest of your program, emulated by me using a while True loop
while True:
print_rate(transfer_rate)
time.sleep(5)
Here you should set the dt argument to whatever seams reasonable for you. I tried using 3 seconds, and this is my output while runnning an online speedtest:
UL: 2 kB/s / DL: 8 kB/s
UL: 3 kB/s / DL: 45 kB/s
UL: 24 kB/s / DL: 1306 kB/s
UL: 79 kB/s / DL: 4 kB/s
UL: 121 kB/s / DL: 3 kB/s
UL: 116 kB/s / DL: 4 kB/s
UL: 0 kB/s / DL: 0 kB/s
The values seems reasonable since my result from the speedtest were DL: 1258 kB/s and UL: 111 kB/s.
The answer provided by Steinar Lima is correct.
But it can be done without threading also:
import time
import psutil
import os
count = 0
qry = ""
ul = 0.00
dl = 0.00
t0 = time.time()
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
up_down = (upload, download)
while True:
last_up_down = up_down
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
t1 = time.time()
up_down = (upload, download)
try:
ul, dl = [
(now - last) / (t1 - t0) / 1024.0
for now, last in zip(up_down, last_up_down)
]
t0 = time.time()
except:
pass
if dl > 0.1 or ul >= 0.1:
time.sleep(0.75)
os.system("cls")
print("UL: {:0.2f} kB/s \n".format(ul) + "DL: {:0.2f} kB/s".format(dl))
v = input()
Simple and easy ;)
I added an LCD mod for this code if you want to test it on a raspberry pi but you need to add the psutil and the lcddriver to your project code!!!!
import time
import psutil
import os
import lcddriver
count=0
qry=''
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
up_down=(upload,download)
display = lcddriver.lcd()
while True:
last_up_down = up_down
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
t1 = time.time()
up_down = (upload,download)
try:
ul, dl = [(now - last) / (t1 - t0) / 1024.0
for now,last in zip(up_down, last_up_down)]
t0 = time.time()
#display.lcd_display_string(str(datetime.datetime.now().time()), 1)
except:
pass
if dl>0.1 or ul>=0.1:
time.sleep(0.75)
os.system('cls')
print('UL: {:0.2f} kB/s \n'.format(ul)+'DL:{:0.2f} kB/s'.format(dl))
display.lcd_display_string(str('DL:{:0.2f} KB/s '.format(dl)), 1)
display.lcd_display_string(str('UL:{:0.2f} KB/s '.format(ul)), 2)
# if KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
# print("Cleaning up!")
# display.lcd_clear()
v=input()
The (effective) network speed is simply bytes transferred in a given time interval, divided by the length of the interval. Obviously there are different ways to aggregate / average the times and they give you different "measures" ... but it all basically boils down to division.
Another and more simple solution (without threading and queues although still based on #Steinar Lima) and for more recent python:
import time
import psutil
def on_calculate_speed(self, interface):
dt = 1 # I find that dt = 1 is good enough
t0 = time.time()
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
return []
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
break
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last
in zip(tot, last_tot)
]
return [int(ul), int(dl)]
t0 = time.time()
while SomeCondition:
# "wlp2s0" is usually the default wifi interface for linux, but you
# could use any other interface that you want/have.
interface = "wlp2s0"
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
Or you could also fetch the default interface with pyroute2:
while SomeCondition:
ip = IPDB()
interface = ip.interfaces[ip.routes['default']['oif']]["ifname"]
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
ip.release()
i found this tread, and dont have any idea from python, i jst copy and paste codes, and now need a little help, this script, i have jst show the total of bytes send/recived, can modify to show the actual speed?
def network(iface):
stat = psutil.net_io_counters(pernic=True)[iface]
return "%s: Tx%s, Rx%s" % \
(iface, bytes2human(stat.bytes_sent), bytes2human(stat.bytes_recv))
def stats(device):
# use custom font
font_path = str(Path(__file__).resolve().parent.joinpath('fonts', 'C&C Red Alert [INET].ttf'))
font_path2 = str(Path(__file__).resolve().parent.joinpath('fonts', 'Stockholm.ttf'))
font2 = ImageFont.truetype(font_path, 12)
font3 = ImageFont.truetype(font_path2, 11)
with canvas(device) as draw:
draw.text((0, 0), cpu_usage(), font=font2, fill="white")
if device.height >= 32:
draw.text((0, 14), mem_usage(), font=font2, fill="white")
if device.height >= 64:
draw.text((0, 26), "IP: " + getIP("eth0"), font=font2, fill=255)
try:
draw.text((0, 38), network('eth0'), font=font2, fill="white")
except KeyError:
# no wifi enabled/available
pass
The code
# pip install speedtest-cli
import speedtest
speed_test = speedtest.Speedtest()
def bytes_to_mb(bytes):
KB = 1024 # One Kilobyte is 1024 bytes
MB = KB * 1024 # One MB is 1024 KB
return int(bytes/MB)
download_speed = bytes_to_mb(speed_test.download())
print("Your Download speed is", download_speed, "MB")
upload_speed = bytes_to_mb(speed_test.upload())
print("Your Upload speed is", upload_speed, "MB")
The first answer in interface should be change to desired network adapter. To see the name in ubuntu you can use ifconfig, then change interface='wifi' to the device name.
a little change to formatting in python3
def print_rate(rate):
try:
print(('UL: {0:.0f} kB/s / DL: {1:.0f} kB/s').format(*rate[-1]))
except IndexError:
'UL: - kB/s/ DL: - kB/s'

Categories