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?
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.
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().
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.
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.
I suspect you have imported the wrong datetime as in:
from datetime import datetime
instead use:
import datetime
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)
.
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