python - 这个错误的解决方法是什么 TypeError: strptime() argument 1 must be str, not datetime.date
问题描述
可以请任何人帮助我的代码吗?这是我得到的错误我只是不明白我是如何得到这个错误的:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
TypeError: strptime() argument 1 must be str, not datetime.date
完整代码:
import datetime
CurrentDate = datetime.datetime.now().date()
print(CurrentDate)
Run4Start = str(CurrentDate) + " 16:00"
Run4End = str(CurrentDate) + " 20:00"
Run4Start = datetime.datetime.strptime(Run4Start, "%Y-%m-%d %H:%M")
Run4End = datetime.datetime.strptime(Run4End, "%Y-%m-%d %H:%M")
print("RUN4 :", CurrentDate )
print(Run4Start, Run4End)
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
print(CurrentDate)
if CurrentDate >= Run4Start and CurrentDate <= Run4End:
print("Hit")
else:
print("Miss!")
解决方案
在:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
CurrentDate
已经是一个datetime.date
对象,在上面创建:
CurrentDate = datetime.datetime.now().date()
并且从未改变过其他任何东西。所以你不需要解析它,它已经“解析”了。只需删除尝试解析它的行。
也就是说,它只是一个date
,并且您正在将它与datetime
特定日期的 s 进行比较;无论它是否有效,它都不会做你可能想做的事情(确定当前时间是否在 1600 到 2000 之间)。您根本不需要字符串解析来做到这一点;您对命中与未命中的整个代码块测试可以简化为:
if datetime.time(16) <= datetime.datetime.now().time() <= datetime.time(20):
print("Hit")
else:
print("Miss!")
因为您只关心时间组件,而不关心日期组件。
推荐阅读
- mysql - 删除 innodb 表以释放磁盘空间是否安全
- reactjs - Redux Store 中的俄语编码问题
- powershell - 一个连接字符串中的多个 DB2 数据库,通过 ODBC 将测试表与 prod 进行比较
- javascript - 如何从 rails 控制器调用 Stripe Checkout
- python - 如何在 Visual Studio Code 中正确设置 Python 调试?
- c++ - Visual Studio 仅通过 WMDC 连接到远程设备一次
- laravel - Laravel - 消息”:“无法使用 3 个可能的身份验证器在用户名 \"me@yahoo.com\" 的 SMTP 服务器上进行身份验证
- python - Pylint 错误地抱怨未定义的变量
- excel - 如何参考父母终止班级?
- python - 如何使用 Python > xlsxwriter 在饼图/甜甜圈图中为不同的数据标签显示不同的字体?