Search code examples
pythonironpythonspotfire

Why cannot I determine in code that an object is of a DataTime type?


I have a variable v and when I do

print type(v)

I do get

<type 'DateTime'>

but when I do

if type(v) in (datetime, datetime.date, datetime.datetime, datetime.time):

it is NOT true

The question is: Why ?

EDIT:

The type DateTime is a Spotfire specific type.

https://docs.tibco.com/pub/doc_remote/spotfire/7.9.0/TIB_sfire-analyst_7.9.0_api/html/F_Spotfire_Dxp_Data_DataType_DateTime.htm


Solution

  • What you would want to use in this case is isinstance

    if isinstance(v, (datetime, datetime.date, datetime.datetime, datetime.time)):
    

    On short, the reason is that type(v) is more restrictive and can't use subclasses, as that DataTime I imagine it is.

    For a detailed overview of type vs isinstance head over to this question.

    Also, note that your type is <type 'DateTime'> and not datetime.datetime. You need to import that DateTime class and used it. Eg:

    from x.y.z import DateTime
    
    if type(v) in (..., DateTime, ...):
        ....