James
James

Reputation: 53

Trouble with datetime in python2.7/django1.5.1

I'm trying to get the number of days in between the current date and a fixed date set in the past.

from datetime import *

past = date(2013, 1, 1)
now = datetime.now()

print now - past

When I run this, I get:

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

Any suggestions are appreciated.

Upvotes: 0

Views: 83

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

Use a datetime.date() object instead. You can use date.today(), or call the datetime().date() method:

>>> from datetime import datetime, date
>>> past = date(2013, 1, 1)
>>> today = date.today()
>>> print today - past
385 days, 0:00:00
>>> now = datetime.now()
>>> print now.date() - past
385 days, 0:00:00

The result of the subtraction is a datetime.timedelta() object, with timedelta().seconds and timedelta().microseconds set to 0, always. The .days attribute gives you just that number of days between the dates:

>>> print (today - past).days
385
>>> print (now.date() - past).days
385

Upvotes: 2

Related Questions