【问题标题】:Action between certain time特定时间之间的动作
【发布时间】:2013-09-10 06:04:38
【问题描述】:

我想要实现的是在时间在 xx 和 yy 之间时运行指定的操作。

(使用 24 小时格式)

例如

  1. 当小时和分钟高于高于 23:30 并且低于低于 06:15 时,运行指定的操作
  2. 当小时和分钟高于 06:15 且低于 09:00 时,运行指定操作
  3. 当小时和分钟高于 09:00 和低于 23:30 时,运行指定操作

我什么时候尝试过:

self.data = 0
localtime = time.strftime("%H%M", time.localtime())
localtime = int(localtime)
if localtime >= 2330 and localtime < 615 and self.data != 1:
     [..] //running certain action
     self.data = 1
elif localtime >= 615 and localtime < 900 and self.data != 2:
     [..] //running certain action
     self.data = 2
elif localtime >= 900 and localtime < 2330 and self.data != 3:
     [..] //running certain action
     self.data = 3

如您所见,我的代码的唯一问题是localtime 不能高于 超过 2330 并且低于 低于 615,依此类推。我得到的唯一其他想法是创建一个列出所有 24 小时的数组,并以这种方式指定某个操作...但是是否有其他方法可以实现我想要的?

【问题讨论】:

  • 在我看来,您希望在第一个条件下使用 or,而不是 and
  • 小语法注释:可以像if 615 &lt;= localtime &lt;= 900一样使用if x &lt; N &lt; y,而不是使用and
  • @Julius 是的,现在看起来轻松有趣...我不知道为什么我没有想到...谢谢!
  • @Sberry 谢谢,看起来很有用,尽管and 是这里的问题,我以后会用这种方式!

标签: python datetime time action


【解决方案1】:

可以使用or 代替and

if (localtime >= 2330 or localtime < 615) and self.data != 1:

if localtime >= 615 and localtime < 900:
     if self.data != 2
         [..] //running certain action
         self.data = 2
elif localtime >= 900 and localtime < 2330:
     if self.data != 3
         [..] //running certain action
         self.data = 3
else:
     if self.data != 1
         [..] //running certain action
         self.data = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多