python判断时间是否落在两个时区之间(只比较时刻不比较日期)

方法1,使用datetime值比较

import datetime
# 范围时间
d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date())+'8:30', '%Y-%m-%d%H:%M')
d_time2 =  datetime.datetime.strptime(str(datetime.datetime.now().date())+'18:33', '%Y-%m-%d%H:%M')

# 当前时间
n_time = datetime.datetime.now()
print('当前时间: '+str(n_time))
# 判断当前时间是否在范围时间内
if n_time > d_time1 and n_time<d_time2:
    print("在此区间中")
else:
    print("不在此区间")

结果如下:

方法2,时间字符串直接比大小

import datetime
t1 = '15:40'
t2 = '18:17'
now = datetime.datetime.now().strftime("%H:%M")
print("当前时间:" + now)
if t1 < now < t2:
    print("在此区间中")
else:
print('不在此区间中')

 

结果如下:

方法3,直接将当前时间格式化成字符串然后转换成整数进行比较。

import time
now = time.strftime("%H%M%S")
print("当前时间:" + now)
#时间区间[09:35:10,18:01:01]
if(180101 > int(time.strftime("%H%M%S")) > 93510):
    print('在此区间中')

结果如下:当前时间15:51:27

参考链接:

参考链接

https://blog.csdn.net/qq_21570029/article/details/83185168

https://blog.csdn.net/daijiguo/article/details/78283788

https://blog.csdn.net/junbujianwpl/article/details/60984757

猜你喜欢

转载自blog.csdn.net/feiyang5260/article/details/87821901