why do i get TypeError: must be str, not builtin_function_or_method?

why do i get TypeError: must be str, not builtin_function_or_method?

我的任务是呈现当前时间和给定的未来时间。 用户输入他想要的额外分钟数,然后我需要显示确切的时间。

我试过以下方法:

import time


hours = int(time.strftime('%H:%M')[0:2])
minutes = int(time.strftime('%H:%M')[3:5])


def newminutes(minutes,adding):
    if minutes + adding >=60:
        return minutes + adding - 60
    else:
        return minutes + adding

def newhours(hours, minutes, adding):
    if minutes + adding >=60:
        newhour = hours + adding//60 + 1     
    else:
        newhour =  hours + adding //60
        if newhour >= 24:
            return newhour - 24
         else:
            return newhour

usersays = input("insert additional minutes: ")
usersay = int(usersays)
finalhours = newhours(hours,minutes,usersay)
finalminutes = newminutes(minutes,usersay)

print("Current Time: " +time.strftime + "\n" +
      "Future Time: "+ str(finalhours) + ":" + str(finalminutes))

输入分钟数后,我得到的输出总是:

Traceback (most recent call last): File "C:\Users\DELL\Documents\Python projects\Ex2\test2.py", line 29, in +":" + str(newminutes(minutes,usersay))) TypeError: must be str, not builtin_function_or_method

我已经尝试修复这个问题好几个小时了,但没有成功,请解释我哪里出错了。提前致谢!

你得到的异常是因为你正试图使用​​带有内置函数的字符串连接:

print("Current Time: " +time.strftime + "\n" +
      "Future Time: "+ str(finalhours) + ":" + str(finalminutes))

time.strftime 是一个函数。

>>> time.strftime
<built-in function strftime>

您需要调用它,以便它 returns 成为一个字符串。 尝试用以下内容替换它,其中 returns 一个字符串对象:

time.strftime("%b %d %Y %H:%M:%S")
'Apr 05 2018 10:57:48'

错误来自向函数添加字符串。有关详细信息,请参阅

通过使用 datetime.time 并通过提供 Format Specification Mini-Language 正确格式化时间来输出正确格式化的对象,您的代码可以简化 很多

import datetime

usersays = input("insert additional minutes: ")
usersay = int(usersays)

now = datetime.datetime.now()  
then = now + datetime.timedelta(minutes = usersay)  # a delta that can be added to time()

# simply format the output correctly
print(f'Current Time: {now.time():%H:%M}\n' + \
      f'Future Time:  {then.time():%H:%M}')

您不需要以这种方式实现所有 time-to-string-to-slice-to-numbers-to-add-minutes-maybe-adding-to-hour-if-needed - 您只需使用 timedelta() 对象添加到时间即可。