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

时间:2015-06-25 04:15:57

标签: python time

由于某种原因,这段代码不起作用,虽然我在调用函数的同时给出了类似的输入。我只需要通过输入两个元组/列表到difference_in_date_tup()来获得时间差异。 代码: -

import time

def getcurrentdate():
    a = time.gmtime(time.time())
    year = a[0]
    month = a[1]
    day = a[2]
    return day,month,year

def difference_in_date_tup(date1, date2):
    """Input dates as tuple/list: (dd,mm,yyy)"""
    a = int(date1[0]) - int(date2[0])
    b = int(date1[1]) - int(date2[1])
    c = int(date1[2]) - int(date2[2])
    return abs(a), abs(b), abs(c)

#This works.
print difference_in_date_tup([25,16,2015],getcurrentdate())

#But not this.
time = raw_input("Enter date in format dd/mm/yyyy: ")
t = time.split("/")
print t
print difference_in_date_tup(t,getcurrentdate())

我收到错误: -

(0, 10, 0)
Enter date in format dd/mm/yyyy: 25/16/2015
['25', '16', '2015']
Traceback (most recent call last):
  File "C:\Users\Ninja\Desktop\test.py", line 24, in <module>
    print difference_in_date_tup(t,getcurrentdate())
  File "C:\Users\Ninja\Desktop\test.py", line 4, in getcurrentdate
    a = time.gmtime(time.time())
AttributeError: 'str' object has no attribute 'gmtime'

1 个答案:

答案 0 :(得分:0)

问题在于 -

time = raw_input("Enter date in format dd/mm/yyyy: ")

在第一行,您要导入模块time,这会将time名称设置为指向module,但在执行上述行后,time名称现在指向用户输入的字符串,因此如果您在此之后尝试访问time,您将获得字符串而不是time模块。

我建议您将此变量重命名为其他内容。