Python:AttributeError:';str';对象没有属性';日期时间';

Python:AttributeError:';str';对象没有属性';日期时间';,python,strptime,Python,Strptime,我正在使用以下代码: def calcDateDifferenceInMinutes(end_date,start_date): fmt = '%Y-%m-%d %H:%M:%S' start_date_dt = datetime.strptime(start_date, fmt) end_date_dt = datetime.strptime(end_date, fmt) # convert to unix timestamp start_date_ts = time

我正在使用以下代码:

def calcDateDifferenceInMinutes(end_date,start_date):
    fmt = '%Y-%m-%d %H:%M:%S'
    start_date_dt = datetime.strptime(start_date, fmt)
    end_date_dt = datetime.strptime(end_date, fmt)

# convert to unix timestamp
start_date_ts = time.mktime(start_date_dt.timetuple())
end_date_ts   = time.mktime(end_date_dt.timetuple())

# they are now in seconds, subtract and then divide by 60 to get minutes.
return (int(end_date_ts-start_date_ts) / 60)
从这个问题:

但我得到的信息是:

AttributeError:“str”对象没有属性“datetime”

我已经回顾了类似的问题,但除了做以下事情外,没有其他选择:

start_date_dt = datetime.datetime.strptime(start_date, fmt)
以下是完整的跟踪:

> Traceback (most recent call last):   File "tabbed_all_cols.py", line
> 156, in <module>
>     trip_calculated_duration = calcDateDifferenceInMinutes (end_datetime,start_datetime)   File "tabbed_all_cols.py", line 41, in
> calcDateDifferenceInMinutes
>     start_date_dt = datetime.datetime.strptime(start_date, fmt) AttributeError: 'str' object has no attribute 'datetime'
有人能告诉我我错过了什么吗

新更新:我仍在努力解决这个问题。我认为这个版本很重要。我使用的是2.7版,正在导入datetime

我认为我没有将字符串日期设置回字符串,这是我认为人们在下面建议的


感谢当您收到一个错误,如
对象没有属性X
,这意味着您正在某处执行类似
某个对象.X
的操作。它还意味着
某个对象是字符串。由于它没有该属性,通常意味着您假设某个对象是另一个对象

完整的错误消息将告诉您是哪一行导致了问题。在您的情况下,是这样的:

start_date_dt = datetime.datetime.strptime(start_date, fmt) AttributeError: 'str' object has no attribute 'datetime'
这里访问
datetime
的唯一对象是第一个
datetime
。这意味着第一个
datetime
是一个字符串,您假设它代表一个模块

如果您要打印出
datetime
(例如:
print(“datetime是:”,datetime)
),我肯定您会看到一个字符串


这意味着,在代码的其他地方,您通过将其设置为字符串(例如:
datetime=“some string”
)覆盖了
datetime

上游的某个地方,您必须已经完成了
datetime=“some string”
您的标题和问题有不同的错误消息。到底是哪一个?大家好:下面是对方法的调用:duration=calcDateDifferenceInMinutes(tend\u datetime,start\u datetime)。我将这些作为字符串传递。请显示完整的堆栈跟踪。它会告诉你哪一行有错误'@zondo-是的,我已经更新了我的标题以反映我遇到的错误。谢谢你捕捉到这一点。在我的例子中,这是因为我不明智地创建了另一个名为“时间”的变量,它包含了我从GPS装置获得的当前时间。代码认为我试图访问这个变量(它是一个字符串),而不是time类。
start_date_dt = datetime.datetime.strptime(start_date, fmt) AttributeError: 'str' object has no attribute 'datetime'