codyc4321
codyc4321

Reputation: 9672

what is the quickest way to check for type(datetime.date) python

I am getting hassle checking types for datetime.date. I don't know if getting good typechecks is a hassle in python or if there's something I'm missing:

In [14]: type(datetime.date)
Out[14]: type

In [15]: type(d)
Out[15]: datetime.date

In [16]: arbitrary = datetime.date(1990, 1, 1)

In [17]: type(arbitrary)
Out[17]: datetime.date

I'd like something simpler than needing to make a fake date within __init__ each time

import datetime

class Month(object):

    def __init__(self, dateobj):
        if type(dateobj) == the type of datetime.date:
            we're good
        else:
            raise Exception('Please feed me a dateobj')

What is the fastest way to check these types, since the type of the base class normally returns a useless type. Thank you

Upvotes: 2

Views: 9935

Answers (2)

midori
midori

Reputation: 4837

Use:

type(your_variable)

Or if you know it supposed to be datetime.date:

isinstance(your_variable, datetime.date)

type gives you the type of variable, isinstance returns True or False. Example:

>>> from datetime import date
>>> today = date.today()
>>> type(today)
<type 'datetime.date'>
>>> isinstance(today, datetime.date)
True

Upvotes: 4

user5903421
user5903421

Reputation:

I use isinstance for type checking:

>>> import datetime
>>> isinstance('2016', datetime.datetime)
False
>>> today = datetime.datetime.now()
>>> isinstance(today, datetime.datetime)
True

Upvotes: 7

Related Questions