所以我是編程新手,我編寫了這個小小的腳本,將我的互聯網從凌晨兩點變成了八點鐘(長篇故事)。使用Datetime/Time模塊時奇怪的類型錯誤?
import os
import datetime as dt
from time import sleep
def connect():
print("Connecting...")
os.system("netsh wlan connect Sushi")
def disconnect():
print("Disconnecting...")
os.system("netsh wlan disconnect")
def checkcon():
attempt= 0
while os.system("ping google.com") != 0:
print("Unable to connect. Trying again.")
connect()
sleep(attempt)
attempt = attempt + 1
if attempt != 0:
print("Attempt ", str(attempt), " ...")
print("Connected successfully")
def timeformat (hr, min, sec) : #For setting proper datetime parameters.
return (str(hr) + ":" + str(min) + ":" + str(sec))
FMT = '%H:%M:%S'
now = timeformat(dt.datetime.now().time().hour, dt.datetime.now().time().minute, dt.datetime.now().time().second)
twoam = '02:00:00'
eightam = '08:00:00'
def tdelta(a, b = now):
tdel = dt.datetime.strptime(a, FMT) - dt.datetime.strptime(b, FMT)
return tdel.seconds
twoto8 = tdelta(eightam, twoam)
nowto8 = tdelta(eightam)
def main():
if twoto8 >= nowto8:
connect()
checkcon()
print("Your internet has been successfully connected")
x = tdelta(nowto8)
sleep(x)
print("Time's up!")
disconnect()
exit()
else:
print("Not yet!")
disconnect()
x = tdelta(nowto8)
sleep(str(x))
main()
main()
但每當我運行它,我得到這個:
線35,在TDELTA TDEL = dt.datetime.strptime(一,FMT) - dt.datetime.strptime(B,FMT) TypeError:必須是str,而不是int
我不明白爲什麼,因爲在函數tdelta中,兩個參數都是字符串,並且...我不知道。我錯過了什麼?我必須指定一些東西嗎?或者這只是我一定錯過的錯字?另外,我認爲只需看一眼我的代碼就可以明顯看出,我是一個絕對的新手,所以如果您有任何改進我的代碼的建議,我將永遠感激不盡。
我真的很感激任何幫助。 :)
編輯:下面是完整的堆棧跟蹤(根據請求):
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\ShutdownTimer.py", line 58, in <module>
main()
File "C:\Users\Lenovo\Desktop\ShutdownTimer.py", line 54, in main
x = tdelta(nowto8)
File "C:\Users\Lenovo\Desktop\ShutdownTimer.py", line 35, in tdelta
tdel = dt.datetime.strptime(a, FMT) - dt.datetime.strptime(b, FMT)
TypeError: must be str, not int
這意味着'tdelta'函數中'a'和'b'參數必須是字符串。 –
你只發布了一部分堆棧跟蹤。看看其餘的。它會直接指向不好的'tdelta'調用。 – user2357112
@NickilMaveli但他們已經不是? – Almond