我正在使用此代码:
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)
Run Code Online (Sandbox Code Playgroud)
来自这个问题:stackoverflow问题
但我收到这条消息:
AttributeError:'str'对象没有属性'datetime'
我已经回顾了类似的问题但除了做以下事情之外没有看到任何其他选择:
start_date_dt = datetime.datetime.strptime(start_date, fmt)
Run Code Online (Sandbox Code Playgroud)
这是完整的痕迹:
> 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'
Run Code Online (Sandbox Code Playgroud)
第41行是:
Run Code Online (Sandbox Code Playgroud)start_date_dt = datetime.datetime.strptime(start_date, fmt)
有人能说清楚我错过了什么吗?
新的更新:我还在努力解决这个问题.我看到那个版本很重要.我正在使用2.7版本并导入日期时间.
我不认为我将字符串日期设置回字符串,这是我认为人们在下面建议的.
谢谢
当你得到一个错误时<str> object has no attribute X,这意味着你正在做某些事情some_object.X.这也意味着它some_object是一个字符串.由于它没有属性,因此通常意味着您假设这some_object是其他内容.
完整的错误消息将告诉您导致问题的行.在你的情况下,它是这样的:
start_date_dt = datetime.datetime.strptime(start_date, fmt) AttributeError: 'str' object has no attribute 'datetime'
Run Code Online (Sandbox Code Playgroud)
这里访问的唯一对象datetime是第一个datetime.这意味着第一个datetime是字符串,你假设它代表一个模块.
如果你要打印出来datetime(例如print("datetime is:", datetime):)我肯定你会看到一个字符串.
这意味着,别的地方在你的代码要覆盖datetime将其设置为一个字符串(例如:datetime = "some string")