如何在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.Nowisn't valid Python syntax—we need to use thedatetimemodule properly.Time()should bedatetime.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/Londonfor GMT/BST,Europe/Madridfor CET/CEST) to match your actual business location. - Daylight Saving Time: Both
zoneinfoandpytzautomatically 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 separateandconditions—it's cleaner and easier to read.
内容的提问来源于stack exchange,提问作者Patrik Drivstedt
相关产品推荐
相关产品推荐

