Add/fix sqlite3 adapters

This commit is contained in:
William Pettersson 2025-03-31 17:49:58 +01:00
parent 051517ec5a
commit 9f3ef9e0e1

View file

@ -44,7 +44,18 @@ values (?, ?, ?, ?, ?)"""
RESCAN = False
def date_from_str(date_str):
def adapt_datetime_iso(val):
"""Adapt datetime.datetime to timezone-aware ISO 8601 date using system timezone??."""
return val.astimezone().strftime("%Y-%m-%d %H:%M:%S.%f%:z")
def adapt_date_iso(val):
"""Adapt datetime.datetime to timezone-aware ISO 8601 date using system timezone??."""
return val.strftime("%Y-%m-%d")
def datetime_from_str(date_str):
date_str = date_str[:22] + date_str[-2:]
try:
date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S%z')
@ -56,6 +67,18 @@ def date_from_str(date_str):
return date
def date_from_str(date_str):
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
print(f"{date_str} to {date}")
return date
sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
sqlite3.register_adapter(datetime.date, adapt_date_iso)
sqlite3.register_converter("datetime", datetime_from_str)
sqlite3.register_converter("date", date_from_str)
def get_file_details(filename):
con = sqlite3.connect(xdg_config_home() / 'gpx_clean' / 'cache.sqlite3')
con.execute(CREATE_SQL)
@ -179,7 +202,7 @@ def _linedata(mode, start, end):
data[exer['describe']] = []
con = sqlite3.connect(xdg_config_home() / 'gpx_clean' / 'cache.sqlite3')
cursor = con.cursor()
end = datetime.datetime(end.year, end.month, end.day, 23, 59, 59)
end = adapt_datetime_iso(datetime.datetime(end.year, end.month, end.day, 23, 59, 59))
cursor.execute(SELECT_PERIOD_SQL, (start, end))
lastday = 0
for row in cursor.fetchall():
@ -331,9 +354,10 @@ def textout(start=datetime.date.today().replace(day=1), end=(datetime.date.today
times = defaultdict(int)
con = sqlite3.connect(xdg_config_home() / 'gpx_clean' / 'cache.sqlite3')
cursor = con.cursor()
start_s = adapt_datetime_iso(datetime.datetime(start.year, start.month, start.day, 0, 0, 0))
# End should be end of day
end = datetime.datetime(end.year, end.month, end.day, 23, 59, 59)
cursor.execute(SELECT_PERIOD_SQL, (start, end))
end = adapt_datetime_iso(datetime.datetime(end.year, end.month, end.day, 23, 59, 59))
cursor.execute(SELECT_PERIOD_SQL, (start_s, end))
for row in cursor.fetchall():
dist, time, speed, date_str = row
date_str = date_str[:22] + date_str[-2:]