I am using this code:
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)
from this question: stackoverflow question
But I'm getting this message:
AttributeError: 'str' object has no attribute 'datetime'
I've reviewed similar questions but don't see any alternatives other than to do something like:
start_date_dt = datetime.datetime.strptime(start_date, fmt)
Here's the full trace:
> 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'
And line 41 is:
start_date_dt = datetime.datetime.strptime(start_date, fmt)
Can someone shed light on what I'm missing?
New Update: I'm still trying to figure this out. I see that version is important. I am using version 2.7 and am importing datetime.
I don't think I am setting the string date back to a string, which is what I think people are suggesting below.
Thanks
When you get an error like <str> object has no attribute X
, that means that somewhere you are doing something like some_object.X
. It also means that some_object
is a string. Since it doesn't have the attribute, it typically means you are assuming that some_object
is something else.
The full error message will tell you what line is causing the problem. In your case, it is this:
start_date_dt = datetime.datetime.strptime(start_date, fmt) AttributeError: 'str' object has no attribute 'datetime'
The only object here that is accessing datetime
is the first datetime
. That means that the first datetime
is a string, and you're assuming it represents a module.
If you were to print out datetime
(eg: print("datetime is:", datetime)
) I'm sure you would see a string.
That means that somewhere else in your code you are overwriting datetime
by setting it to a string (eg: datetime = "some string"
)