Python: AttributeError: 'str' object has no attribute 'datetime'

Viewed 28752

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

1 Answers
Related