0

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.

0

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1. You can write : print (now.date() - past).days if you want to display days only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.