首页 > 解决方案 > 这个错误的解决方法是什么 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!")

标签: pythondatetime

解决方案


在:

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!")

因为您只关心时间组件,而不关心日期组件。


推荐阅读