AttributeError:'str'对象没有属性'sleep'

时间:2015-12-29 07:32:41

标签: python python-3.x

我按照此问题的标题中指定AttributeError: 'str' object has no attribute 'sleep',我无法弄清楚为什么会抛出该错误消息。

Countdown Timer.py

import time, datetime

Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50

while True:
    Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
    diff = Datetime - datetime.datetime.now()
    diff = str(diff)

    days, not_useful, time = diff.split()

    Day1 = days + " " + "Day" # Day

    print(Day1)

    time.sleep(1)

3 个答案:

答案 0 :(得分:6)

那是因为你在本地删除了包含模块的变量time。这是一个正确的代码:

import time, datetime

Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50

while True:
    Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
    diff = Datetime - datetime.datetime.now()
    diff = str(diff)

    days, not_useful, time_str = diff.split()

    Day1 = days + " " + "Day" # Day

    print(Day1)

    time.sleep(1)

答案 1 :(得分:1)

days, not_useful, time = diff.split()

这里你将'time'作为字符串。改变动词名称......

答案 2 :(得分:-1)

这是因为您在代码中使用Time作为变量:

time = diff.split()

并且上面的行在时间模块中局部覆盖变量time

尝试使用其他变量:

time_1 = diff.split()