views:

59

answers:

1

What's the equivalent type in types module for datetime? Example:

import datetime
import types
t=datetime.datetime.now()
if type(t)==types.xxxxxx:
    do sth

I didn't find the relevent type in types module for the datetime type; could any one help me?

+3  A: 
>>> type(t)
<type 'datetime.datetime'>
>>> type(t) is datetime.datetime
True

Is that the information you're looking for? I don't think you'll be able to find the relevant type within the types module since datetime.datetime is not a builtin type.

Edit to add: Another note, since this is evidently what you were looking for (I wasn't entirely sure when I first answered) - type checking is generally not necessary in Python, and can be an indication of poor design. I'd recommend that you review your code and see if there's a way to do whatever it is you need to do without having to use type checking.

Also, the typical (canonical? pythonic) way to do this is with:

>>> isinstance(t, datetime.datetime)
True

See also: Differences between isinstance() and type() in python, but the main reason is that isinstance() supports inheritance whereas type() requires that both objects be of the exact same type (i.e. a derived type will evaluate to false when compared to its base type using the latter).

eldarerathis
In this case, it would be preferable to say `type(t) is datetime.datetime` vs. using `==`.
ma3
@ma3204: Yeah, I think you're right. I'll change that.
eldarerathis
it would be preferably to use `isinstance`
SilentGhost
@eldar: *pythonic*
SilentGhost
agreed. `isinstance` is better than `is`
ma3