Working on a problem where I have to evaluate whether a time stamp (UTC) exceeds 7PM Americas/New_York
.
I naively did my check as:
if (timestamp - timedelta(hours=4)).time() > 19:
__logic__
Which obviously failed with daylight savings EST/EDT.
I think this works but feels wrong.
EST = pytz.timezone('America/New_York')
biz_end = datetime(1990, 1, 1, 19, tzinfo=EST).astimezone(pytz.utc).hour
if timestamp.time() > biz_end:
__logic__
Is there a better solution here?
It should be far simpler to work directly in desired TZ rather than fighting time differences and DST as this would mostly add a headache for no other benefits:
import pytz
from datetime import datetime, time
# Get the UTC timestamp and convert to target TZ
timestamp_utc = datetime.utcnow().replace(tzinfo=pytz.utc)
timestamp_ny = timestamp_utc.astimezone(pytz.timezone('America/New_York'))
if timestamp_ny.time() > time(19, 0):
# It's past 7PM...
pass
Also, if you use pytz
only for this, you can use Python 3.9+ built-in libraries and drop pytz
dependency, which as @FObersteiner linked in above comment, would also free you from Weird timezone issue with pytz problems:
from datetime import datetime, time
from zoneinfo import ZoneInfo
timestamp_utc = datetime.now(timezone.utc)
timestamp_ny = timestamp_utc.astimezone(ZoneInfo('America/New_York'))
if timestamp_ny.time() > time(19, 0):
pass