Skip to main content
 首页 » 编程设计

python之确定日期时间是否在工作日时间表内

2024年12月31日11落叶无声

我想知道给定的日期时间是否在时段安排及其时区内指定。

例子:

确定 epoch=1537414453837 是否在下面定义的时间表内:

时段时区:Asia/Hong_Kong(可能会更改)

时段安排:

mon: 0900-2300 
tue: 0900-2300 
wed: 0900-2300 
thu: 0900-2300 
fri: 0900-2300 
sat: 1000-2300 
sun: 1000-2300 

请您参考如下方法:

纪元时间独立于时区。它是从 UTC 时区的 1970 年 1 月 1 日午夜开始计算的。无论您当前身在何处,它都显示相同的纪元时间。但是您可以将给定的纪元时间转换为其他时区。

使用 pytz.all_timezones 查看所有可用时区。

以下是其中一种方法。

from datetime import datetime 
import pytz 
epoch_time=1537414453837/1000  
weekdays = ('Monday','Tuesday','Wednesday','Thursday', 'Friday') 
weekends = ('Saturday', 'Sunday') 
 
local_time=datetime.fromtimestamp(epoch_time, tz= pytz.timezone('Hongkong')) 
hours = local_time.hour 
 
day = datetime.fromtimestamp(epoch_time).strftime("%A") 
if (day in weekdays): 
    if (hours in range(9,23)): 
        print("its Dayparting Schedule and a weekday") 
elif (day in weekends): 
    if (hours in range(10,23)): 
        print("its Dayparting Schedule and a weekend") 
else: 
    print("no such day")