由于datetime是日期对象的实例,我如何确定它实际上不是日期?
例如:
from datetime import datetime, date
today = date.today()
now = datetime.now()
if isinstance(now, date) # returns True!
today-now # Fails, because it's not a date
这自然会返回TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
最好的解决方案是强制第二个操作数为date
,以便减法始终有效。
today - date(now.year, now.month, now.day)
当now
是date
或datetime
对象,或者实际上是任何像它们一样嘎嘎作响的类型(即具有包含指定有效日期的整数的year
、month
和day
属性)时,这将起作用。
您可以使用type()
测试显式类型,而不允许使用子类:
if type(now) is date:
或者,只需捕捉TypeError
:
if isinstance(now, date):
try:
today - now
except TypeError:
# hrm, `now` is a subclass that is not supported
或明确排除datetime
:
if isinstance(now, date) and not isinstance(now, datetime):
或者使用.date()
方法(如果可用):
try:
# support `datetime` objects too
now = now.date()
except AttributeError:
pass
today - now