使用Datetime/Time模块时出现奇怪的TypeError?

2024-10-01 02:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对编程很陌生,我编写了一个小脚本,让我的互联网从凌晨2点到8点(说来话长)

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号线 tdel=日期时间(a,FMT)-日期时间(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

Tags: datetimetimeosmaindefconnectdtsleep
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:01

第46行和第54行(x = tdelta(nowto8))使用整数参数而不是字符串调用tdelta。将第46-47行从

x = tdelta(nowto8)
sleep(x)

sleep(nowto8)

第54-55行

x = tdelta(nowto8)
sleep(str(x))

sleep(nowto8)

同样如此。你知道吗

相关问题 更多 >