5

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?

codekaizen
  • 26,990
  • 7
  • 84
  • 140
mlzboy
  • 14,343
  • 23
  • 76
  • 97

1 Answers1

14
>>> 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).

Community
  • 1
  • 1
eldarerathis
  • 35,455
  • 10
  • 90
  • 93