fromisoformat-replace-z (FURB162)
派生自 refurb 代码检查工具。
修复总是可用的。
作用
检查 datetime.fromisoformat()
调用,其中唯一的参数是 Z
的内联替换,使用零偏移时区。
为什么这不好?
在 Python 3.11 及更高版本中,datetime.fromisoformat()
可以处理大多数 ISO 8601 格式,包括带有 Z
的格式,因此这种操作是不必要的。
有关不支持格式的更多信息,请参见官方文档。
示例
from datetime import datetime
date = "2025-01-01T00:00:00Z"
datetime.fromisoformat(date.replace("Z", "+00:00"))
datetime.fromisoformat(date[:-1] + "-00")
datetime.fromisoformat(date.strip("Z", "-0000"))
datetime.fromisoformat(date.rstrip("Z", "-00:00"))
建议改为
修复安全性
此修复始终标记为不安全,因为它可能会更改程序的行为。
例如,正常工作的代码可能会变为无法工作
d = "Z2025-01-01T00:00:00Z" # Note the leading `Z`
datetime.fromisoformat(d.strip("Z") + "+00:00") # Fine
datetime.fromisoformat(d) # Runtime error