1

I'm experimenting with the Datetime module in Python and decided to make a program to count days forward and backward. Relevant code:

if bORf == 'f':
    howfarforward = input("How far forward would you like to count?: ")
    def countforward(howfarfor):
        day = datetime.date.today()
        day -= howfarfor
        print(day)
    countback(howfarfor)

I am getting the error

Traceback (most recent call last):
  File "datecount.py", line 11, in <module>
    countback(howfarback)
  File "datecount.py", line 9, in countback
    day -= howfarback
TypeError: unsupported operand type(s) for -=: 'datetime.date' and 'str'

And I know why, I just don't know how to fix it. How do I do this?

Rest of Code:

import datetime
print("Today is", datetime.date.today())
bORf = input("Would you like to count backwards or forwards? (b/f)")
if bORf == 'b':
    howfarback = input("How far back would you like to count?: ")
        def countback(howfarback):
            day = datetime.date.today()
            day -= howfarback
            print(day)
        countback(howfarback)
...
2
  • Where's the rest of your code? Commented Mar 15, 2012 at 1:52
  • It's great that you reduced your code to a mostly-sscce, but it's not totally self-consistent, which makes this a bit hard to answer consistently. Commented Mar 15, 2012 at 1:58

2 Answers 2

4

Use datetime.timedelta, and you need to parse the input to a number:

>>> import datetime
>>> howfarforward = int(input("How far forward would you like to count?: "))
How far forward would you like to count?: 4
>>> day = datetime.date.today()
>>> day = day + datetime.timedelta(days=howfarforward)
>>> day
datetime.date(2012, 3, 18)
Sign up to request clarification or add additional context in comments.

Comments

1

You can't subtract a string from a datetime. Try converting it into a timedelta first.

Comments

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.