You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytz获取当前时间处于指定区间的所有时区的优化方法

实现方案

你不需要逐小时多次遍历时区集合,仅需一次遍历就能完成时间范围判断,效率更高:

基础版本(适用于不跨天的时间范围,例:上午9点到下午2点)

from datetime import datetime
import pytz

# 获取当前UTC时间
now_utc = datetime.now(pytz.utc)
# 定义目标时间范围:9点 ~ 14点(包含两个端点)
start_hour = 9
end_hour = 14

# 一次遍历筛选符合条件的时区
target_timezones = [
    tz for tz in pytz.common_timezones_set
    if start_hour <= now_utc.astimezone(pytz.timezone(tz)).hour <= end_hour
]

进阶版本(支持跨天的时间范围,例:晚上10点到次日凌晨2点)

如果你的筛选范围跨零点,只需调整判断逻辑即可:

from datetime import datetime
import pytz

now_utc = datetime.now(pytz.utc)
# 定义跨天范围:22点 ~ 次日2点
start_hour = 22
end_hour = 2

target_timezones = [
    tz for tz in pytz.common_timezones_set
    for tz_time in [now_utc.astimezone(pytz.timezone(tz))]
    if (start_hour < end_hour and start_hour <= tz_time.hour <= end_hour)
    or (start_hour > end_hour and (tz_time.hour >= start_hour or tz_time.hour <= end_hour))
]

精度扩展(支持精确到分钟/秒)

如果需要更精细的时间范围判断(比如9:30到14:15),可以直接提取时间部分比较,不用仅取小时:

from datetime import datetime, time
import pytz

now_utc = datetime.now(pytz.utc)
start_time = time(9, 30)
end_time = time(14, 15)

target_timezones = [
    tz for tz in pytz.common_timezones_set
    for tz_time in [now_utc.astimezone(pytz.timezone(tz)).time()]
    if (start_time < end_time and start_time <= tz_time <= end_time)
    or (start_time > end_time and (tz_time >= start_time or tz_time <= end_time))
]

内容的提问来源于stack exchange,提问作者jack west

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:06:03