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'
# ...
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.
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.
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)
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!-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With