Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python isinstance() returning error with datetime.date

Tags:

python

I am trying to compile an old 2008 code.

import datetime

if isinstance(value, datetime.date):

But I got an error:

isinstance() arg 2 must be a class, type, or tuple of classes and types Python Executable: /usr/bin/python2.6 Python Version: 2.6.5

What am I missing?

like image 265
Josir Avatar asked Apr 14 '11 15:04

Josir


People also ask

How do you check if a variable is a datetime in Python?

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.

What is datetime datetime now () in Python?

Python datetime: datetime. now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today().

Should I use Isinstance in Python?

If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It's because isinstance() function also checks if the given object is an instance of the subclass.

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


2 Answers

I suspect you have imported the wrong datetime as in:

from datetime import datetime

instead use:

import datetime
like image 86
Gregory Ray Avatar answered Oct 08 '22 17:10

Gregory Ray


To clarify this more, you must be careful if datetime is referring to the module from import datetime or the datetime class from from datetime import datetime as both have a date attribute.

In the first case, datetime.date refers to the date class which can be used with isinstance:

import datetime
type(datetime.date)
Out[13]: type

In the second case, the datetime.date refers to the date method of the datetime class which cannot be used with isinstance and hence the error.

from datetime import datetime
type(datetime.date)
Out[15]: method_descriptor

To help avoid errors like this it's best to explictly import and use the date class using from datetime import date then use isinstance(value, date).

like image 36
frmdstryr Avatar answered Oct 08 '22 17:10

frmdstryr