Skip to content

Commit

Permalink
Fix datetime comparisons (tz naive vs tz aware) after utcnow() repl…
Browse files Browse the repository at this point in the history
…acement.
  • Loading branch information
aussig committed Dec 31, 2024
1 parent e98a78b commit 56e192d
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 8 deletions.
11 changes: 6 additions & 5 deletions bgstally/activity.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import json
import re
from copy import deepcopy
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from typing import Dict

from bgstally.constants import ApiSizeLookup, ApiSyntheticEvent, ApiSyntheticCZObjectiveType, ApiSyntheticScenarioType, FILE_SUFFIX, CheckStates
from bgstally.constants import ApiSizeLookup, ApiSyntheticEvent, ApiSyntheticCZObjectiveType, ApiSyntheticScenarioType, DATETIME_FORMAT_JOURNAL, FILE_SUFFIX, CheckStates
from bgstally.debug import Debug
from bgstally.missionlog import MissionLog
from bgstally.state import State
Expand Down Expand Up @@ -570,7 +570,7 @@ def bv_received(self, journal_entry: Dict, state: State, cmdr: str):

# Check whether in megaship scenario for scenario tracking
if state.last_megaship_approached != {}:
timedifference: datetime = datetime.strptime(journal_entry['timestamp'], "%Y-%m-%dT%H:%M:%SZ") - datetime.strptime(state.last_megaship_approached['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
timedifference: datetime = datetime.strptime(journal_entry['timestamp'], DATETIME_FORMAT_JOURNAL) - datetime.strptime(state.last_megaship_approached['timestamp'], DATETIME_FORMAT_JOURNAL)
if timedifference > timedelta(minutes=5):
# Too long since we last entered a megaship scenario, we can't be sure we're fighting at that scenario, clear down
state.last_megaship_approached = {}
Expand Down Expand Up @@ -618,7 +618,7 @@ def cb_received(self, journal_entry: dict, state: State, cmdr: str):

# Otherwise, must be on-ground or in-space CZ for CB kill tracking
if state.last_settlement_approached != {}:
timedifference = datetime.strptime(journal_entry['timestamp'], "%Y-%m-%dT%H:%M:%SZ") - datetime.strptime(state.last_settlement_approached['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
timedifference = datetime.strptime(journal_entry['timestamp'], DATETIME_FORMAT_JOURNAL) - datetime.strptime(state.last_settlement_approached['timestamp'], DATETIME_FORMAT_JOURNAL)
if timedifference > timedelta(minutes=5):
# Too long since we last approached a settlement, we can't be sure we're fighting at that settlement, clear down
state.last_settlement_approached = {}
Expand All @@ -629,7 +629,7 @@ def cb_received(self, journal_entry: dict, state: State, cmdr: str):
self._cb_ground_cz(journal_entry, current_system, state, cmdr)

elif state.last_spacecz_approached != {}:
timedifference = datetime.strptime(journal_entry['timestamp'], "%Y-%m-%dT%H:%M:%SZ") - datetime.strptime(state.last_spacecz_approached['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
timedifference = datetime.strptime(journal_entry['timestamp'], DATETIME_FORMAT_JOURNAL) - datetime.strptime(state.last_spacecz_approached['timestamp'], DATETIME_FORMAT_JOURNAL)
if timedifference > timedelta(minutes=5):
# Too long since we last entered a space cz, we can't be sure we're fighting at that cz, clear down
state.last_spacecz_approached = {}
Expand Down Expand Up @@ -1476,6 +1476,7 @@ def _from_dict(self, dict: Dict):
"""
self.tick_id = dict.get('tickid')
self.tick_time = datetime.strptime(dict.get('ticktime'), DATETIME_FORMAT_ACTIVITY)
self.tick_time = self.tick_time.replace(tzinfo=UTC)
self.tick_forced = dict.get('tickforced', False)
self.discord_webhook_data = dict.get('discordwebhookdata', {})
self.discord_notes = dict.get('discordnotes', "")
Expand Down
6 changes: 5 additions & 1 deletion bgstally/missionlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,11 @@ def _expire_old_missions(self):
# Old missions pre v1.11.0 and missions with missing expiry dates don't have Expiry stored. Set to 7 days ahead for safety
if not 'Expiry' in mission or mission['Expiry'] == "": mission['Expiry'] = (datetime.now(UTC) + timedelta(days = TIME_MISSION_EXPIRY_D)).strftime(DATETIME_FORMAT_JOURNAL)

timedifference = datetime.now(UTC) - datetime.strptime(mission['Expiry'], DATETIME_FORMAT_JOURNAL)
# Need to do this shenanegans to parse a tz-aware timestamp from a string
expiry_timestamp: datetime = datetime.strptime(mission['Expiry'], DATETIME_FORMAT_JOURNAL)
expiry_timestamp = expiry_timestamp.replace(tzinfo=UTC)

timedifference = datetime.now(UTC) - expiry_timestamp
if timedifference > timedelta(days = TIME_MISSION_EXPIRY_D):
# Keep missions for a while after they have expired, so we can log failed missions correctly
self.missionlog.remove(mission)
4 changes: 3 additions & 1 deletion bgstally/objectivesmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ def get_human_readable_objectives(self) -> str:
mission_system: str|None = mission.get('system')
mission_faction: str|None = mission.get('faction')
mission_startdate: datetime = datetime.strptime(mission.get('startdate', datetime.now(UTC).strftime(DATETIME_FORMAT_API)), DATETIME_FORMAT_API)
mission_enddate: datetime|None = datetime.strptime(mission.get('enddate', None), DATETIME_FORMAT_API)
mission_startdate = mission_startdate.replace(tzinfo=UTC)
mission_enddate: datetime = datetime.strptime(mission.get('enddate', datetime(3999, 12, 31, 23, 59, 59, 0, UTC).strftime(DATETIME_FORMAT_API)), DATETIME_FORMAT_API)
mission_enddate = mission_enddate.replace(tzinfo=UTC)
if mission_enddate < datetime.now(UTC): continue
mission_activity: Activity = self.bgstally.activity_manager.query_activity(mission_startdate)

Expand Down
6 changes: 5 additions & 1 deletion bgstally/targetmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,10 @@ def _expire_old_targets(self):
Clear out all old targets from the target log
"""
for target in reversed(self.targetlog):
timedifference = datetime.now(UTC) - datetime.strptime(target['Timestamp'], DATETIME_FORMAT_JOURNAL)
# Need to do this shenanegans to parse a tz-aware timestamp from a string
target_timestamp: datetime = datetime.strptime(target['Timestamp'], DATETIME_FORMAT_JOURNAL)
target_timestamp = target_timestamp.replace(tzinfo=UTC)

timedifference: datetime = datetime.now(UTC) - target_timestamp
if timedifference > timedelta(days = TIME_TARGET_LOG_EXPIRY_D):
self.targetlog.remove(target)
2 changes: 2 additions & 0 deletions bgstally/tick.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def fetch_tick(self):
return None

tick_time: datetime = datetime.strptime(tick_time_raw, DATETIME_FORMAT_TICK_DETECTOR)
tick_time = tick_time.replace(tzinfo=UTC)

if tick_time > self.tick_time:
# There is a newer tick
Expand Down Expand Up @@ -75,6 +76,7 @@ def load(self):
"""
self.tick_id = config.get_str("XLastTick")
self.tick_time = datetime.strptime(config.get_str("XTickTime", default=self.tick_time.strftime(DATETIME_FORMAT_TICK_DETECTOR)), DATETIME_FORMAT_TICK_DETECTOR)
self.tick_time = self.tick_time.replace(tzinfo=UTC)


def save(self):
Expand Down

0 comments on commit 56e192d

Please sign in to comment.