Billjk
Billjk

Reputation: 10686

Datetime Module Python

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)
...

Upvotes: 1

Views: 715

Answers (2)

Matt Ball
Matt Ball

Reputation: 359826

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)

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798656

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

Upvotes: 1

Related Questions