Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I check that a given argument is a datetime.date object?

I'm currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn't an instance of datetime. Surely there's a better way?

from datetime import date, datetime

def some_func(arg):
    assert isinstance(arg, date) and not isinstance(arg, datetime),\
        'arg must be a datetime.date object'
    # ...
like image 616
rmh Avatar asked May 04 '10 01:05

rmh


People also ask

How do you check if an object is a datetime object?

Use the isinstance built-in function to check if a variable is a datetime object in Python, e.g. if isinstance(today, datetime): . The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

How do you check that a value is a date object in node?

The validity of the date in the Date object can be checked with the ! isNan() function. It returns true if the date is not invalid.

What is a datetime datetime object?

date Objects. A date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions. January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. 2 class datetime. date (year, month, day)


2 Answers

I don't understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that's really what you insist on doing, then:

if type(arg) is not datetime.date:
    raise TypeError('arg must be a datetime.date, not a %s' % type(arg))

Don't use assert except for sanity check during development (it gets turned to a no-op when you run with python -o), and don't raise the wrong kind of exception (such as, an AssertionError when a TypeError is clearly what you mean here).

Using isinstance and then excluding one specific subclass is not a sound way to get a rigidly specified exact type with subclasses excluded: after all, the user might perfectly well subclass datetime.date and add whatever it is you're so keep to avoid by rejecting instances of datetime.datetime specifically!-)

like image 179
Alex Martelli Avatar answered Sep 24 '22 06:09

Alex Martelli


If your problem is that the graph goes wonky because it is using fractions of a day, you can test for that in other ways e.g. hasattr(arg, 'hour') distinguishes between a datetime instance and a date instance.

like image 29
John Machin Avatar answered Sep 25 '22 06:09

John Machin