【问题标题】:Convert string "AM" or "PM" then add to time without date转换字符串“AM”或“PM”,然后添加到没有日期的时间
【发布时间】: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


【解决方案1】:

datetime 可能会造成混淆,因为模块和类都称为 datetime。

将您的导入更改为from datetime import datetime, time。导入也应该放在最顶端,但这不是绝对必要的。

当分配ct_timedue_time时,你使用str(datetime.time(args)),它应该只是str(time(args))

strptime 来自日期时间,而不是时间,所以将time.strptime(args) 更改为datetime.strptime(args)

也像 DeepSpace & martineau 所说,您需要在格式字符串中添加 '%p' 以说明 AM/PM 部分。

最终代码:

from datetime import datetime, time

current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"

ct_time = str(time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(time(due_hour, due_minute))+due_section
print(due_time)

ct_time_str = datetime.strptime(ct_time, '%H:%M:%S%p')

due_time_str= datetime.strptime(due_time,'%H:%M:%S%p')

if (ct_time_str < due_time_str):
   print("still have time to turn in assignment")
else:
   print("too late")

编辑: 将if (ct_time_str &lt; due_time_str): 更改为if (ct_time_str &gt; due_time_str):

【讨论】:

  • 感谢码没有错误,当我使用print(due_time_str)时为什么它返回1900-01-01 09:00:00?不是上午 9:00:00。
  • datetime 对象包含一个日期和一个时间,如果您只想要时间组件,请使用due_time_str.time()。我刚刚注意到的另一件事是您在 if 语句中的比较是错误的,应该是 ct_time 大于。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 2017-01-16
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多