[Python-ideas] bool(datetime.time(0, 0))

Steven D'Aprano steve at pearwood.info
Mon May 7 20:31:51 CEST 2012


Alexander Belopolsky wrote:
> On Mon, May 7, 2012 at 1:31 PM, Steven D'Aprano <steve at pearwood.info> wrote:

>> For code where some_time could be None, write this:
>>
>>    if not (some_time is None or some_time == _MIDNIGHT):
>>        ...
>>
>>
>> Have I missed any common cases?
> 
> 
> Yes, your code will raise an exception if some_time has tzinfo set.
> This is exactly the issue that I expected you to miss, so I rest my
> case. :-)

But if you set the timezone, midnight is not necessarily false.


py> class GMT5(datetime.tzinfo):
...     def utcoffset(self,dt):
...         return timedelta(hours=5)
...     def tzname(self,dt):
...         return "GMT +5"
...     def dst(self,dt):
...         return timedelta(0)
...
py> gmt5 = GMT5()
py> bool(datetime.time(0,0, tzinfo=gmt5))
True
py> bool(datetime.time(5, 0, tzinfo=gmt5))
False


So I assume anyone using tzinfo will probably know enough not to be testing 
against time objects directly. Or at least not be using bool(some_some) to 
detect midnight.




-- 
Steven




More information about the Python-ideas mailing list