【问题标题】:How to check if the current time is in range in python using time strings?python - 如何使用时间字符串检查当前时间是否在python范围内?
【发布时间】:2015-12-22 17:39:06
【问题描述】:

我需要一种方法来确定当前时间是否在使用时间字符串的时间窗口范围内。例如,开始时间为“0:00”,结束时间为“3:15”。

我遇到了这个解决方案,How to check if the current time is in range in python?,它很棒,但它不使用时间字符串。 python中有什么东西我可以传递两个时间字符串然后检查它们之间是否有什么东西吗?还有其他建议吗?

谢谢。

【问题讨论】:

  • time.strptime 是你的朋友,还有一些其他的转换可以把它变成time.time() 格式,这样你就可以做if start < time.time() > end 逻辑。

标签: python string time window range


【解决方案1】:

不确定您使用的是哪个版本的 Python,所以我在 python3 中进行了处理。

import time

old_time = time.strptime('01:00', '%H:%M')
new_time = time.strptime('06:00', '%H:%M')

print(old_time)
print(new_time)

if old_time > new_time:
    print('old time is old')
else:
    print('new is cool')

【讨论】:

    【解决方案2】:

    这是 time 模块的一个有用方法: https://docs.python.org/2/library/time.html#time.strptime

    以下是它的用法示例:

    import time
    new_time = time.strptime("0:00", "%H:%M")
    other_time = time.strptime("3:15", "%H%M")
    
    print(new_time > other_time)
    print(other_time > new_time)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      相关资源
      最近更新 更多