Skip to content

Commit 670d747

Browse files
Niloth-ptimabbott
authored andcommitted
google-calendar: Generalize the datetime parsing for event fields.
Moved the parsing logic into `get_start_or_end` to enable re-using the function when we add support for the `end` field of event.
1 parent fd59d10 commit 670d747

File tree

1 file changed

+19
-22
lines changed

1 file changed

+19
-22
lines changed

zulip/integrations/google/google-calendar

+19-22
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import sys
99
import time
1010
from configparser import ConfigParser
1111
from dataclasses import dataclass
12-
from typing import List, Optional, Set, Tuple, TypedDict
12+
from typing import Any, Dict, List, Optional, Set, Tuple, TypedDict
1313

1414
import dateutil.parser
1515
import pytz
@@ -212,31 +212,28 @@ def populate_events() -> Optional[None]:
212212

213213
events.clear()
214214
for event in feed["items"]:
215-
try:
216-
start = dateutil.parser.parse(event["start"]["dateTime"])
217-
# According to the API documentation, a time zone offset is required
218-
# for start.dateTime unless a time zone is explicitly specified in
219-
# start.timeZone.
220-
if start.tzinfo is None:
221-
event_timezone = pytz.timezone(event["start"]["timeZone"])
222-
# pytz timezones include an extra localize method that's not part
223-
# of the tzinfo base class.
224-
start = event_timezone.localize(start)
225-
except KeyError:
226-
# All-day events can have only a date.
227-
start_naive = dateutil.parser.parse(event["start"]["date"])
228-
229-
# All-day events don't have a time zone offset; instead, we use the
230-
# time zone of the calendar.
231-
calendar_timezone = pytz.timezone(feed["timeZone"])
232-
# pytz timezones include an extra localize method that's not part
233-
# of the tzinfo base class.
234-
start = calendar_timezone.localize(start_naive)
215+
216+
def get_start_or_end(event: Dict[str, Any], field_name: str) -> datetime.datetime:
217+
try:
218+
field = dateutil.parser.parse(event[field_name]["dateTime"])
219+
# a time zone offset is required unless timeZone is explicitly specified.
220+
if field.tzinfo is None:
221+
# pytz timezones include an extra localize method that's not part
222+
# of the tzinfo base class.
223+
event_timezone = pytz.timezone(event[field_name]["timeZone"])
224+
field = event_timezone.localize(field)
225+
except KeyError:
226+
# All-day events can have only a date.
227+
field_naive = dateutil.parser.parse(event[field_name]["date"])
228+
# All-day events do not have a time zone offset; use the calendar's time zone.
229+
calendar_timezone = pytz.timezone(feed["timeZone"])
230+
field = calendar_timezone.localize(field_naive)
231+
return field
235232

236233
events.append(
237234
{
238235
"id": event["id"],
239-
"start": start,
236+
"start": get_start_or_end(event, "start"),
240237
"summary": event.get("summary", "(No Title)"),
241238
}
242239
)

0 commit comments

Comments
 (0)