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

如何在Python中设置欧盟时区每日固定营业时间(00:01-11:00)

Fixing Your EU Time Business Hours Check in Python

Hey Patrik, let's get that business hours logic working correctly for EU time! Your core idea is solid, but there are a couple of key issues in your code—most importantly, timezone handling (since relying on local time will break if your server isn't in the EU) and some Python syntax tweaks.

Let's break down the problems in your original code:

  • DateTime.Now isn't valid Python syntax—we need to use the datetime module properly.
  • Time() should be datetime.time() (part of Python's standard library).
  • You're not accounting for EU timezone offsets (like CET/CEST for daylight saving time), which means your check will be wrong if your server runs in a different timezone.

Corrected Code (Python 3.9+)

We'll use Python's built-in zoneinfo module (no extra installs needed) to target a specific EU timezone (e.g., Europe/Berlin for central EU time—adjust this to your actual EU region if needed):

from datetime import datetime, time
from zoneinfo import ZoneInfo

# Define your EU timezone (adjust to your region: Europe/Paris, Europe/London, etc.)
eu_timezone = ZoneInfo("Europe/Berlin")

# Get current time in the specified EU timezone
today_eu = datetime.now(eu_timezone).time()

# Define your business hours (EU time)
from_time = time(0, 1, 0)  # 00:01
to_time = time(11, 0, 0)   # 11:00

# Check if current time is within business hours
is_in_time_interval = from_time <= today_eu <= to_time

if not is_in_time_interval:
    # Return closed page
    return self.GetPage('stangd')
# Return next page if open
return PageNode.GetNextPage(self)

For Older Python Versions (Pre-3.9)

If you're stuck on Python <3.9, use the pytz library (install first with pip install pytz):

from datetime import datetime, time
import pytz

# Define EU timezone
eu_timezone = pytz.timezone("Europe/Berlin")

# Get current EU time
today_eu = datetime.now(eu_timezone).time()

from_time = time(0, 1, 0)
to_time = time(11, 0, 0)

is_in_time_interval = from_time <= today_eu <= to_time

if not is_in_time_interval:
    return self.GetPage('stangd')
return PageNode.GetNextPage(self)

Key Notes:

  • Timezone Selection: Pick the correct EU timezone from the IANA timezone database (e.g., Europe/London for GMT/BST, Europe/Madrid for CET/CEST) to match your actual business location.
  • Daylight Saving Time: Both zoneinfo and pytz automatically handle DST changes, so your hours will stay accurate year-round.
  • Simplified Comparison: In Python, you can chain the time comparison (from_time <= today_eu <= to_time) instead of using two separate and conditions—it's cleaner and easier to read.

内容的提问来源于stack exchange,提问作者Patrik Drivstedt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:07:51