【问题标题】:How to compare two times [duplicate]如何比较两次[重复]
【发布时间】:2020-01-18 16:07:42
【问题描述】:

我正在尝试在 python 中比较两次:

from datetime import time, datetime

start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()

if (current_time == start):
    print("Time Matched")

现在,当我运行代码并且时间达到上述开始时间时,它不会打印“时间匹配”请帮助我解决我试图用这段代码做的事情是当开始时间与我的笔记本电脑匹配时当我试图执行一些代码时,买我做不到。

【问题讨论】:

  • now() 可能有几秒钟和几毫秒,这会有所不同。
  • 这能回答你的问题吗? Python time comparison
  • 如果你想在python中比较日期,我建议你使用日期对象而不是日期时间,因为日期时间需要帐户小时,分钟,秒,毫秒,......很难获得相同的日期本案

标签: python datetime timedelta


【解决方案1】:

**您的电脑以毫秒为单位记下停机时间,这就是您无法获得所需结果的原因**

如果您在日期时间 obj 中提供第二个,则 -\

from datetime import time, datetime

start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
start_str=str(start)
current_str=str(surrent_time)
if(start_str==current_str):
      print(match)

**通用方法**

如果我们想匹配特定部分这是23小时格式如果你想要12小时格式你可以找到diff参数answer

 start = datetime(2020, 1 , 18, 9,30)
 current = datetime.now()
 start_year=start.strftime("%Y")
 start_month=start.strftime("%m")
 start_day=start.strftime("%H")
 start_hours=start.strftime("%H")
 start_min=start.strftime("%M")
 print(start_year,start_month,start_day,start_hours,start_min)


 current_year=current.strftime("%Y")
 current_month=current.strftime("%m")
 current_day=current.strftime("%H")
 current_hours=current.strftime("%H")
 current_min=current.strftime("%M")
 print(current_year,current_month,current_day,current_hours,current_min)

if((start_year==current_year) and (start_month==current_month)  and (start_day==current_day) and (start_hours==current_hours) and (start_min==current_min)):
      print("match")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多