假设我有一个函数,它需要两个日期时间并以秒为单位返回差:
import datetime
def diff(d1: datetime.datetime, d2: datetime.datetime) -> float:
return (d2 - d1).total_seconds()
if __name__ == '__main__':
d1 = datetime.datetime.now()
d2 = datetime.datetime.now(datetime.timezone.utc)
print(diff(d1, d2))
mypy 告诉我这很好:
$ python3.8 -m mypy test.py
Success: no issues found in 1 source file
但我得到一个类型错误:
TypeError: can't subtract offset-naive and offset-aware datetimes
错误消息中清楚地说明了原因。类型注释不够好。
我想这是一个很常见的情况。是否有推荐的方法来注释时区感知与不感知日期时间对象,从而正确使用 mypy?