johndone
johndone

Reputation: 13

subtracting datetime fields

I've spent the good part of the last 3 hours searching and I just can't seem to figure out why my code won't work.

import datetime
#get time since last status change
@property
def last_update(self):
    if self.statuschange_set.exists():
        last_change = self.statuschange_set.all()[0]
        return last_change.date_changed - self.created
    #if no status change has occurred, use creation date
    if not self.statuschange_set.exists():
        df = DateFormat(datetime.now())
        df = df.format("d/m/Y, P ") 
        return df - self.created
    return ""

The code breaks at the bottom where I'm trying to subtract todays date from the creation date. I tested it where I'm able to subtract self.created from itself however the code above spits out an exception value:

 Exception Value:   
 unsupported operand type(s) for -: 'unicode' and 'datetime.datetime'

I've obviously got the formating wrong of df wrong however even from looking at the other solutions on stackoverflow, I'm unable to come up with a solution to my issue.

Upvotes: 1

Views: 35

Answers (1)

Sayse
Sayse

Reputation: 43300

The formatting makes no sense, you can just keep it as a datetime

return datetime.now() - self.created

If you really need the formatting, you should do this after the calculation

df = DateFormat(datetime.now() - self.created)
...
return df

Upvotes: 3

Related Questions