如何检查当前时间是否在python范围内? [英] How to check if the current time is in range in python?

查看:154
本文介绍了如何检查当前时间是否在python范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查当前时间是否在timerange中。最简单的例子time_end> time_start:

I need to check if the current time is in timerange. The most simple case time_end > time_start:

if time(6,0) <= now.time() <= time(12,00): print '1'

但当用户输入时间范围时,结束时间小于开始时间,例如23:00 - 06:00。像00:00这样的时间将在这个范围内。大约5年前我写了这个PHP函数:

But troubles begin when user enters a time range when the end time is smaller than the start time, e.g. "23:00 - 06:00". A time like '00:00' will be in this range. About 5 years ago I wrote this PHP function:

function checkInterval($start, $end)
  {    
    $dt = date("H:i:s");    

    $tstart = explode(":", $start);
    $tend =   explode(":", $end);
    $tnow =   explode(":", $dt);

    if (!$tstart[2])
      $tstart[2] = 0;

    if (!$tend[2])
      $tend[2] = 0;  

    $tstart = $tstart[0]*60*60 + $tstart[1]*60 + $tstart[2];
    $tend   = $tend[0]*60*60   + $tend[1]*60   + $tend[2];
    $tnow   = $tnow[0]*60*60   + $tnow[1]*60   + $tnow[2];

    if ($tend < $tstart)
      {
        if ($tend - $tnow > 0 && $tnow > $tstart)
          return true;
        else if ($tnow - $tstart > 0 && $tnow > $tend)
          return true;
        else if ($tend > $tnow && $tend < $tstart && $tstart > $tnow)
          return true;
        else return false;
      } else
      {
        if ($tstart < $tnow && $tend > $tnow)
          return true;
        else
          return false;
      }

现在我需要做同样的事情,但我想让它很好看着。那么,我应该使用什么算法来确定当前时间'00:00'是否在反向范围内。 ['23:00','01:00']

Now I need to do the same thing, but I want to make it good looking. So, what algorithm should I use to determine if the current time '00:00' is in reversed range e.g. ['23:00', '01:00']?

推荐答案

p> Python解决方案要短得多,

The Python solution is going to be much, much shorter.

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

code> datetime.time class start end x

Use the datetime.time class for start, end, and x.

>>> import datetime
>>> start = datetime.time(23, 0, 0)
>>> end = datetime.time(1, 0, 0)
>>> time_in_range(start, end, datetime.time(23, 30, 0))
True
>>> time_in_range(start, end, datetime.time(12, 30, 0))
False

这篇关于如何检查当前时间是否在python范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆