【发布时间】:2020-11-17 22:11:20
【问题描述】:
我正在寻找将 am/pm 字符串转换为时间的方法,以便我可以在一天中的 2 个不同时间之间进行比较。我尝试使用 time.strptime 或类似的东西,但似乎它们都需要日期和时间。
我的代码如下:
current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"
import datetime
ct_time = str(datetime.time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(datetime.time(due_hour, due_minute))+due_section
print(due_time)
ct_time_str = time.strptime(ct_time, '%H:%M:%S') # how to format this to time?
due_time_str= time.strptime(due_time,'%H:%M:%S') # how to format this to time?
if (ct_time_str>due_time_str):
print("still have time to turn in assignment")
else:
print("too late")
出现以下错误,不知道如何从str 转换为'time'。
Traceback (most recent call last):
File "main.py", line 15, in <module>
ct_time_str = time.strptime(ct_time, '%H:%M:%S')
NameError: name 'time' is not defined
【问题讨论】:
-
您遇到错误了吗?如果是这样,你得到什么错误?我的猜测是这不是因为日期,而是因为你没有解析
AM/PM部分(%p指令)。见How to Ask。 -
正如@DeepSpace:建议,使用
time.strptime(ct_time, '%H:%M:%S%p')。 -
仍然出现同样的错误,表示时间未定义:ct_time_str = time.strptime(ct_time, '%H:%M:%S%p') NameError: name 'time' is not defined
标签: python python-3.x time