Just a warning, my code uses the pyperclip module but you don't have to pip install it because it is just for cosmetic reasons to make it a little easier. It also reads a file but the contents in the file is not important right now and can be replaced with any file with strings separated by lines.
What I want my code to do is:
WORKING 1. I want to be able to enter in a value for each line in the file, the first number representing hours and the second representing minutes.
NOT WORKING 2. I want to start a timer for for the hours and minutes for each time inputted. After I will add a sound but that is not there yet.
Problem: I input 1 minute for it to count down and it randomly stops in the middle of the count down. I don't know why because sometimes it finishes and sometimes it doesn't.
Code: https://pastebin.com/A2tTHtmK
import re
import pyperclip
from collections import OrderedDict
import time
import sys
import winsound
islandAndTimes = {}
fileObject = open("C:\\Users\\harry\\Desktop\\Skyblock Island bossmob warps.txt", "r")
message = fileObject.read()
whatToSearch = re.compile(r'\/is warp \w+')
l1 = whatToSearch.findall(message)
for eachInList in l1:
pyperclip.copy(eachInList)
typeIslandTime = input("How long until it spawns? (hours, minutes) ")
islandAndTimes[eachInList] = typeIslandTime
newIslandAndTimes = OrderedDict(sorted(islandAndTimes.items(), key=lambda t: t[1]))
if typeIslandTime == "0":
del islandAndTimes[eachInList]
print(newIslandAndTimes)
for everyIsland in newIslandAndTimes:
for firstKey, firstValue in newIslandAndTimes.items():
print("\n")
print(firstKey)
splitValues = firstValue.split()
newHours = int(splitValues[0])
newSecond = 0
newMins = int(splitValues[1])
print(newHours, newMins)
hour = time.strftime("%H")
minute = time.strftime("%M")
print("The hour is " + hour + " the minute is " + minute)
newerHours = newHours + int(hour)
newerMinute = newMins + int(minute)
print("total secodns is " + str(int((int(newHours) * 60 * 60) + int(newMins) * 60)-20))
totalSeconds = int(newHours) * 60 * 60 + int(newMins) * 60-20
while newSecond != 19:
time.sleep(1)
if int(hour) < newerHours or int(minute) < newerMinute:
#int(hour) > newerHours or int(minute) > newerMinute
minute = time.strftime("%M")
hour = time.strftime("%H")
second = time.strftime("%S")
sys.stdout.write('\r' + str("Time until ring: " + str(newHours) + " " + str(newMins) + " " + str(newSecond)))
sys.stdout.flush()
if newSecond == 0:
newSecond = 60
newMins = newMins - 1
elif newMins == 0 and newHours > 0:
newHours = newHours - 1
newSecond = newSecond - 1
print('completed')
Related
I want to track the traffic from my NIC's since I started the Python script.
But psutil.net_io_counters().bytes_recv dosn't start at 0 byte to count. I only can change it to zero by restarting my NIC.
import re
from time import sleep
import psutil, sys
last_received = psutil.net_io_counters().bytes_recv
last_sent = psutil.net_io_counters().bytes_sent
last_total = last_received + last_sent
while True:
received = psutil.net_io_counters().bytes_recv
sent = psutil.net_io_counters().bytes_sent
total = received + sent
last_received = received
last_sent = sent
last_total = total
income = round((received / 1024 / 1024),2) #Traffic in MB
outcome = round((sent / 1024 / 1024),2) #Traffic out MB
totalIO = round((total / 1024 / 1024),2) #Total traffic MB
print("Received: " + str(income) + " MB")
print("Sent: " + str(outcome) + " MB")
sleep(1)
Good morning as per the attached code, I would like to create a function that if the work shift (Bezahltezeit variable is showed in the Überziet column in Excel) is more than 10 hours, a 25% surcharge is created for every minute worked after ten hours.
I should have a result in minutes so that I can then add it up and convert it to excel.
Also in the nachtzeit column the 10% surcharge is calculated for every minute worked between 10 am and 6 am, as you see in the table it is transcribed in hours and minutes, I should have the result in minutes again so that I can add it up and convert to excel.
The function was created with the help of user #constantstranger whom I thank again!
Thanks
Year = int(IcsStartData.year)
Month = int(IcsStartData.month)
Day = int(IcsStartData.day)
StartH = int(IcsStartData.hour)
StartM = int(IcsStartData.minute)
EndH = int(IcsEndData.hour)
EndM = int(IcsEndData.minute)
currentDateTime = datetime.now()
Date_Time_Stamp = currentDateTime.strftime("%d%m%Y%H%M")
Current_DateTime = currentDateTime.strftime("%d.%m.%Y %H:%M")
Datetime = IcsStartData.strftime("%d.%m.%Y")
StartTime = IcsStartData.strftime("%H.%M")
EndTime = IcsEndData.strftime("%H.%M")
Schichtdauer = IcsSchichtDauer.strftime("%H.%M")
Bezahltezeit = IcsBezahlteZeit.strftime("%H.%M")
Bezahltezeit_Stunden = float(IcsBezahlteZeit.strftime("%H"))
Bezahltezeit_Minuten = float(IcsBezahlteZeit.strftime("%M"))
Terminaldata = IcsEndData.strftime("%d.%m.%Y")
EndDay = int(IcsEndData.day)
EndMonth = int(IcsEndData.month)
EndYear = int(IcsEndData.year)
def excelworking():
endTime = IcsEndData
startTime = IcsStartData
def getRegularAndBonusHours(startTime, endTime):
if endTime < startTime:
raise ValueError(f'endTime {endTime} is before startTime {startTime}')
startDateStr = startTime.strftime("%d.%m.%Y")
bonusStartTime = datetime.strptime(startDateStr + " " + "20:00", "%d.%m.%Y %H:%M")
prevBonusEndTime = datetime.strptime(startTime.strftime("%d.%m.%Y") + " " + "06:00", "%d.%m.%Y %H:%M")
bonusEndTime = prevBonusEndTime + timedelta(days=1)
NachtArbeitZeit = timedelta(days=0)
dienstdauer = endTime - startTime
hours = dienstdauer.total_seconds() // 3600
if hours > 24:
fullDays = hours // 24
NachtArbeitZeit += fullDays * (bonusEndTime - bonusStartTime)
endTime -= timedelta(days=fullDays)
if startTime < prevBonusEndTime:
NachtArbeitZeit += prevBonusEndTime - startTime
if endTime < prevBonusEndTime:
NachtArbeitZeit -= prevBonusEndTime - endTime
if startTime > bonusStartTime:
NachtArbeitZeit -= startTime - bonusStartTime
if endTime > bonusStartTime:
NachtArbeitZeit += min(endTime, bonusEndTime) - bonusStartTime
return dienstdauer, NachtArbeitZeit
def getHours(startTime, endTime, extraFraction):
dienstdauer, NachtArbeitZeit = getRegularAndBonusHours(startTime, endTime)
delta = dienstdauer + NachtArbeitZeit * extraFraction
return delta
def testing(start, end):
dienstdauer, NachtArbeitZeit = getRegularAndBonusHours(start, end)
def getHoursRoundedUp(delta):
return delta.days * 24 + delta.seconds // 3600 + (1 if delta.seconds % 3600 else 0)
regularHours, nachtszulage = getHoursRoundedUp(dienstdauer), getHoursRoundedUp(NachtArbeitZeit)
# print(f'start {start}, end {end}, nachtszulage {nachtszulage}, Nachstüberzeit {NachtArbeitZeit / 60 * 10} dienstdauer: {dienstdauer} {NachtArbeitZeit}')
# Writing on a EXCEL FILE
filename = (f"{myPath}/Monatsplan {username} {month} {year}.xlsx")
emptycell = ' '
wegzeiten = (int('13'))
try:
wb = load_workbook(filename)
ws = wb.worksheets[0] # select first worksheet
except FileNotFoundError:
headers_row = ['Datum','Dienst','Funktion','Von','Bis','Schichtdauer','Bezahlte Zeit (Studen)','Bezahlte Zeit (Minuten)','Zeit Konvertierung','Überzeit (ab 10 St.)','Nachtzeitzuschlag.','Nachtdienstentschädigung','Wegzeiten']
wb = Workbook()
ws = wb.active
ws.append(headers_row)
wb.save(filename)
ws.append([f'{Datetime}',f'{string1}'f'{tagesinfo2}',f'{soup_funktion}',f'{StartTime}',f'{EndTime}',f'{Schichtdauer}',f'{Bezahltezeit_Stunden}',f'{Bezahltezeit_Minuten}',f'{emptycell}',f'{emptycell}',f'{NachtArbeitZeit / 60 * 10}',f'{nachtszulage}',f'{wegzeiten}'])
for cols in ws.iter_cols( ):
if cols[-1].value:
cols[-1].border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))
cols[-1].number_format = '0.00'
wb.save(filename)
wb.close()
I'm trying to make a Timecode calculator using python but I don't get why the output is wrong:
class Time:
def __init__(self, hour=0, minute=0, second=0, image=0):
self.hour = hour
self.minute = minute
self.second = second
self.image = image
def __str__(self):
return "{:02d}:{:02d}:{:02d}:{:02d}".format(self.hour, self.minute, self.second, self.image)
def __add__(self, second_time):
new_time = Time()
#define image add for 24 FPS
if(self.image + second_time.image) >= 24:
self.second += 1
new_time.image = (self.image + second_time.image) - 24
else:
new_time.image = self.image + second_time.image
#define second add for 24 FPS
if(self.second + second_time.second) >= 60:
self.minute += 1
new_time.second = (self.second + second_time.second) - 60
else:
new_time.second = self.second + second_time.second
#define minutes add for 24 FPS
if(self.minute + second_time.minute) >= 60:
self.hour += 1
new_time.minute = (self.minute + second_time.minute) - 60
else:
new_time.minute = self.minute + second_time.minute
#define hours add for 24 FPS
if(self.hour + second_time.hour) >= 24:
new_time.hour = (self.hour + second_time.hour) - 24
else:
new_time.hour = self.hour + second_time.hour
return new_time
time1 = Time(2, 23, 21, 10)
time2 = Time(2, 21, 2, 22)
test = time1 + time2
print(time1)
if I print time1 before "test = time1 + time2" time1 = 02:23:21:10 but when I print it after test like in the code above the value of time 1 is 02:23:22:10...
did I miss something? why would the value of time1 change?
Thanks for your help
I have a Python script that is used to find some stresses on a structure (a crane boom) when exposed to the wind from all directions. This means it creates 360 text files, 1 for each degree the structure is facing. Instead of doing 360 consecutive loops running on a single core, I want to break the task up into maybe 10 or 20 processes. Is there a way I could modify the following code so it created and ran multiple scripts with different degree ranges i.e. one script would do 0 to 20 degrees, the next 20 to 40 etc.?
import math
import csv
boomDirection = 0
time = 0
maxStress = 650
with open("SomeWindAndHeadingStressMatrix.csv") as f:
data = [row for row in csv.reader(f)]
while boomDirection < 361:
file = open("SomeWindSpeedSourceData.txt", 'r')
data_file = open("Bolt Stress - " + str(boomDirection) + " Degrees.csv", 'w')
line = file.readline()
while line != '':
try:
if len(line.split(','))>1:
windSpeedHigh = int(int(line.split(',')[19])*1.32)
windSpeedLow = int(int(line.split(',')[22])*1.32)
windDirection = int(line.split(',')[14]) - boomDirection
if windDirection < 0:
windDirection += 360
stressHigh = float(data[windSpeedHigh][windDirection])
stressLow = float(data[windSpeedLow][windDirection])
if time % 10080 == 0:
data_file.write(str(time) + ', ' + str(maxStress) + ('\n'))
time += 0.5
else:
data_file.write(str(time) + ', ' + str(round(stressHigh,1)) + ('\n'))
time += 0.5
data_file.write(str(time) + ', ' + str(round(stressLow,1)) + ('\n'))
time += 0.5
except ValueError:
pass
line = file.readline()
data_file.close()
time = 0
boomDirection = boomDirection + 1
I have this code so far. I need to write a program which prints the billing information for a machine which is hired out.
hours = 23
minutes = 81
seconds = 0
seconds_in_minute = 60
seconds_in_hour = 3600
final_seconds = seconds % 60
final_seconds2 = ((2 - len(str(final_seconds))) * "0") + str(final_seconds)
extra_minutes = int(seconds / 60)
final_minutes = (minutes + extra_minutes) % 60
final_minutes2 = ((2 - len(str(final_minutes))) * "0") + str(final_minutes)
extra_hours = int(minutes / 60)
final_hours = (hours + extra_hours)
final_hours2 = ((2 - len(str(final_hours))) * "0") + str(final_hours)
cost_for_seconds = 2
cost_for_seconds_in_full_minute = 1.6
cost_for_seconds_in_full_hour = 1.2
seconds_cost = cost_for_seconds * final_seconds
minutes_cost = cost_for_seconds_in_full_minute * (final_minutes * seconds_in_minute)
hours_cost = cost_for_seconds_in_full_hour * (final_hours * seconds_in_hour)
cost_for_seconds = 2
cost_for_seconds_in_full_minute = 1.6
cost_for_seconds_in_full_hour = 1.2
seconds_cost = cost_for_seconds * final_seconds
minutes_cost = cost_for_seconds_in_full_minute * (final_minutes * seconds_in_minute)
hours_cost = cost_for_seconds_in_full_hour * (final_hours * seconds_in_hour)
print("hours =", hours)
print("minutes =", minutes)
print("seconds =", seconds)
print("=" * 35)
print(" ", " ", "Total time: ", final_hours2, ":", final_minutes2, ":", final_seconds2 , sep = "")
print(" ", " ", "Cost: ", "$", int(seconds_cost + minutes_cost + hours_cost), sep = "")
print("=" * 35)
Which produces the output of
hours = 23
minutes = 81
seconds = 0
===================================
Total time: 24:21:00
Cost: $101376
===================================
Problem is I need it to be in the format 00:21:00
I need it so that the cost is still the same, but the hours display is never 24 hours or over.
I think what you are looking for is the modulo operation.
After calculating final_hours, you need to do :
final_hours = final_hours % 24
Your final hours will always be a value beetween 0 and 23
Just add a day for every 24 hours:
Here is a code snippet that will normalize seconds, minutes, hours, days:
extra_minutes, seconds = divmod(seconds, 60)
extra_hours, minutes = divmod(minutes + extra_minutes, 60)
extra_days, hours = divmod(hours + extra_hours, 24)
days += extra_days
and here is a way to make a string with time in HH:MM:SS zero-padded format:
"{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
Hope it helps.