Make datetime objects timezone-aware (#2565)

Comparing timestamps returned by the API with naive datetime objects (without timezone information) will raise an error. Add `tzinfo=datetime.timezone.utc` to your datetime instance.

Co-authored-by: John T. Wodder II <git@varonathe.org>
This commit is contained in:
Enrico Minack
2023-06-28 21:47:48 +02:00
committed by GitHub
co-authored by John T. Wodder II
parent 99155806ed
commit 0177f7c513
67 changed files with 668 additions and 456 deletions
+7 -19
View File
@@ -38,8 +38,8 @@
# #
################################################################################
import datetime
import typing
from datetime import datetime, timezone
from operator import itemgetter
from typing import (
TYPE_CHECKING,
@@ -53,6 +53,8 @@ from typing import (
Union,
)
from dateutil import parser
from . import Consts
from .GithubException import BadAttributeException, IncompletableObject
@@ -225,28 +227,14 @@ class GithubObject:
@staticmethod
def _makeTimestampAttribute(value: int) -> Attribute[int]:
return GithubObject.__makeTransformedAttribute(
value, int, datetime.datetime.utcfromtimestamp
value,
int,
lambda t: datetime.fromtimestamp(t, tz=timezone.utc),
)
@staticmethod
def _makeDatetimeAttribute(value: Optional[Union[int, str]]) -> Attribute:
def parseDatetime(s):
if (
len(s) == 24
): # pragma no branch (This branch was used only when creating a download)
# The Downloads API has been removed. I'm keeping this branch because I have no mean
# to check if it's really useless now.
return datetime.datetime.strptime(
s, "%Y-%m-%dT%H:%M:%S.000Z"
) # pragma no cover (This branch was used only when creating a download)
elif len(s) >= 25:
return datetime.datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S") + (
1 if s[19] == "-" else -1
) * datetime.timedelta(hours=int(s[20:22]), minutes=int(s[23:25]))
else:
return datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ")
return GithubObject.__makeTransformedAttribute(value, str, parseDatetime)
return GithubObject.__makeTransformedAttribute(value, str, parser.parse)
def _makeClassAttribute(self, klass: Any, value: Any) -> Attribute:
return GithubObject.__makeTransformedAttribute(