42Cummer commited on
Commit
2c59439
·
verified ·
1 Parent(s): 0b4af70

Upload utils.py

Browse files
Files changed (1) hide show
  1. api/utils.py +24 -3
api/utils.py CHANGED
@@ -1,5 +1,25 @@
1
  from datetime import datetime, time, timedelta
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  def hms_to_seconds(hms_str):
4
  """Converts GTFS 'HH:MM:SS' (e.g. '25:30:00') to total seconds from midnight."""
5
  h, m, s = map(int, hms_str.split(':'))
@@ -22,13 +42,14 @@ def get_service_day_start_ts():
22
  import pytz
23
  eastern_tz = pytz.timezone("America/Toronto")
24
  except ImportError:
25
- # Last resort: hardcoded UTC-5 (EST), no DST handling
26
  now_utc = datetime.now(timezone.utc)
27
- if now_utc.hour < 9: # 4 AM Eastern = 9 AM UTC (EST)
 
28
  service_date = now_utc.date() - timedelta(days=1)
29
  else:
30
  service_date = now_utc.date()
31
- service_start_utc = datetime.combine(service_date, time.min, tzinfo=timezone.utc) + timedelta(hours=5)
32
  return int(service_start_utc.timestamp())
33
 
34
  # Get current UTC time and convert to Eastern
 
1
  from datetime import datetime, time, timedelta
2
 
3
+ def _eastern_utc_offset(now_utc):
4
+ """
5
+ Returns the UTC offset in hours for Eastern time (EST=-5, EDT=-4).
6
+ Uses North American DST rules: starts second Sunday in March at 2 AM EST (07:00 UTC),
7
+ ends first Sunday in November at 2 AM EDT (06:00 UTC).
8
+ """
9
+ year = now_utc.year
10
+ from datetime import timezone
11
+ march_1 = datetime(year, 3, 1, tzinfo=timezone.utc)
12
+ first_sun_mar = march_1 + timedelta(days=(6 - march_1.weekday()) % 7)
13
+ dst_start = first_sun_mar + timedelta(weeks=1, hours=7)
14
+
15
+ nov_1 = datetime(year, 11, 1, tzinfo=timezone.utc)
16
+ first_sun_nov = nov_1 + timedelta(days=(6 - nov_1.weekday()) % 7)
17
+ dst_end = first_sun_nov + timedelta(hours=6)
18
+
19
+ if dst_start <= now_utc < dst_end:
20
+ return 4 # EDT
21
+ return 5 # EST
22
+
23
  def hms_to_seconds(hms_str):
24
  """Converts GTFS 'HH:MM:SS' (e.g. '25:30:00') to total seconds from midnight."""
25
  h, m, s = map(int, hms_str.split(':'))
 
42
  import pytz
43
  eastern_tz = pytz.timezone("America/Toronto")
44
  except ImportError:
45
+ # Last resort: pure-Python DST-aware Eastern offset
46
  now_utc = datetime.now(timezone.utc)
47
+ utc_offset = _eastern_utc_offset(now_utc)
48
+ if now_utc.hour < (4 + utc_offset): # 4 AM Eastern in UTC
49
  service_date = now_utc.date() - timedelta(days=1)
50
  else:
51
  service_date = now_utc.date()
52
+ service_start_utc = datetime.combine(service_date, time.min, tzinfo=timezone.utc) + timedelta(hours=utc_offset)
53
  return int(service_start_utc.timestamp())
54
 
55
  # Get current UTC time and convert to Eastern