0

My error-handling works, but something is wrong.

import datetime
def d(date):
    return datetime.datetime.strptime(date, "%d/%m/%Y")


def test(prompt):
    while True:
        try:
            value = input(prompt)
            a = d(value)
            break
        except ValueError or TypeError:
            print("Wrong format")
    return a

b = test("Write date")

def func():
    a = d(b)
    if d('1/12/2020') <= a <= d('28/02/2021'):
        print("ok")
    else:
        print("no")

func()

When I put b in another function I get:

return datetime.datetime.strptime(datumet, "%d/%m/%Y")
TypeError: strptime() argument 1 must be str, not datetime.datetime. 

But without error handling it works. What can be wrong with the code?

  • 1
    The error clearly comes from `func`, which you don't show us, so we can't help you. Either way, `datumet` is already `datetime` according to the error, so you don't need to call `strptime` – DeepSpace Nov 18 '20 at 17:19
  • I will show you the function –  Nov 18 '20 at 17:21
  • What do you think is wrong? –  Nov 18 '20 at 17:33
  • You need to add error handling for `TypeError` somewhere — either in the `d()` function itself or everywhere an attempt is made to use it. – martineau Nov 18 '20 at 17:40
  • @martineau, I placed: except ValueError or TypeError (in the test-function) but it did not work. –  Nov 18 '20 at 17:43
  • Without see what changes you made, I am unable comment further… – martineau Nov 18 '20 at 17:49
  • This `except ValueError or TypeError:` is not the correct way of catching multiple exceptions. See [Catch multiple exceptions in one line (except block)](https://stackoverflow.com/q/6470428/2745495). – Gino Mempin Nov 19 '20 at 00:21

1 Answers1

0

Your test function returns a datetime object. In the func function, you're trying to take the datetime object you've passed in and call the d() function on it, but d() expects a string as its input.

Look at this line:

b = test("Write date")

b is a datetime, because that's what test returned to it. Then when you call

func(b)

you're passing in that datetime. Then, inside func you have:

if d('1/12/2020') <= d(date) <= d('1/12/2021'):

The first call to d('1/12/2020') works because d expects to get a string. The second call, d(date) fails, because date isn't a string: it's the datetime you passed in. The third call to d('1/12/2021') would succeed but you're never getting that far because the second call fails.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65