48 python判斷時間是否落在兩個時區之間(只比較時刻不比較日期)


https://blog.csdn.net/feiyang5260/article/details/87821901

 

方法1,使用datetime值比較(一般不如2好)

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,時間字符串直接比大小(最好用)

如果是 7:00  一定要寫成 07:00

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

示例

從txt讀取指定時間段,判斷是否在里面

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime  #時間

time_begin="8:00"
time_over ="22:00"

#函數名 讀取txt中指定參數內容
#函數輸入
# path_txt  txt文件地址
# canshu    要從txt讀取的內容
# fengefu   參數名字和值的分隔符號 默認 -
#函數輸出
# 返回字符型結果

def readtxt(path_txt,canshu):
    #/home/pi/Desktop/info
    fengefu="-"
    f = open(path_txt, mode='r+', encoding='utf-8')  # 打開txt文件,以‘utf-8’編碼讀取
    lines = f.readlines()   # 以行的形式進行讀取文件
     
    for line in lines:
        a=line.strip().split(fengefu)    # x.strip()#除去每行的換行符 按照:分割
        b = a[0:1] # list--str
        c = "".join(b).strip()  # 去除空格
        
        if  c==canshu:
            b = a[1:2]   # 這是選取需要讀取的位數
            c="".join(b).strip()  # 去除空格   
            #print(c)
            return c
    f.close()
    

def main():
    #讀取開始時間 字符型 數字需要轉化 int()
    time_begin=readtxt("/home/pi/Work/WorkPlace/python/2waibao/2face_lab/info","time_begin")
    print(time_begin)
    #讀取結束時間
    time_over=readtxt("/home/pi/Work/WorkPlace/python/2waibao/2face_lab/info","time_over")
    print(time_over)
    #獲取當前和時間
    now = datetime.datetime.now().strftime("%H:%M")
    print("當前時間:" + now)
    #比較是否在時間段內
    if time_begin < now < time_over:
        print("在此區間中")
    else:
        print("不在此區間中")


main()

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM