Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether a variable is an instance of datetime.datetime or datetime.date

I've tried

In [16]: import datetime

In [17]: now = datetime.datetime.utcnow()

In [18]: isinstance(now, datetime.date)
Out[18]: True

In [19]: isinstance(now, datetime.datetime)
Out[19]: True

What I expected is that the first isinstance should return False. What happened?

like image 866
waitingkuo Avatar asked Mar 27 '13 08:03

waitingkuo


1 Answers

Since datetime inherits from date, every instance of datetime also is an instance of date, i.e. you can use datetime instances wherever you would use date instances. This is a central concept in object-oriented programming.

To modify the check to do what you want, you can test specifically for date by using type(now) is datetime.date. Or, you can explicitly exclude datetime with isinstance(now, datetime.date) and not isinstance(now, datetime.datetime).

like image 149
user4815162342 Avatar answered Oct 11 '22 01:10

user4815162342