diff --git a/tests/scrobbles_tests/test_utils.py b/tests/scrobbles_tests/test_utils.py new file mode 100644 index 0000000..57444cd --- /dev/null +++ b/tests/scrobbles_tests/test_utils.py @@ -0,0 +1,12 @@ +from datetime import datetime +import pytz +from django.contrib.auth import get_user_model + +from vrobbler.apps.scrobbles.utils import timestamp_user_tz_to_utc + + +def test_timestamp_user_tz_to_utc(): + timestamp = timestamp_user_tz_to_utc( + 1685561082, pytz.timezone("US/Eastern") + ) + assert timestamp == datetime(2023, 5, 31, 23, 24, 42, tzinfo=pytz.utc) diff --git a/vrobbler/apps/scrobbles/tsv.py b/vrobbler/apps/scrobbles/tsv.py index b432706..f64ba3d 100644 --- a/vrobbler/apps/scrobbles/tsv.py +++ b/vrobbler/apps/scrobbles/tsv.py @@ -13,6 +13,8 @@ from music.utils import ( from scrobbles.constants import AsTsvColumn from scrobbles.models import Scrobble +from vrobbler.apps.scrobbles.utils import timestamp_user_tz_to_utc + logger = logging.getLogger(__name__) @@ -65,9 +67,9 @@ def process_audioscrobbler_tsv_file(file_path, user_id, user_tz=None): ) continue - timestamp = datetime.utcfromtimestamp( - int(row[AsTsvColumn["TIMESTAMP"].value]) - ).replace(tzinfo=user_tz) + timestamp = timestamp_user_tz_to_utc( + int(row[AsTsvColumn["TIMESTAMP"].value]), user_tz + ) new_scrobble = Scrobble( user_id=user_id, diff --git a/vrobbler/apps/scrobbles/utils.py b/vrobbler/apps/scrobbles/utils.py index a12a45f..3a1a419 100644 --- a/vrobbler/apps/scrobbles/utils.py +++ b/vrobbler/apps/scrobbles/utils.py @@ -1,10 +1,10 @@ import logging -from datetime import timedelta +from datetime import datetime, timedelta, tzinfo from urllib.parse import unquote +import pytz from dateutil.parser import ParserError, parse from django.apps import apps -from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.utils import timezone @@ -17,6 +17,12 @@ logger = logging.getLogger(__name__) User = get_user_model() +def timestamp_user_tz_to_utc(timestamp: int, user_tz: tzinfo) -> datetime: + return user_tz.localize(datetime.utcfromtimestamp(timestamp)).astimezone( + pytz.utc + ) + + def convert_to_seconds(run_time: str) -> int: """Jellyfin sends run time as 00:00:00 string. We want the run time to actually be in seconds so we'll convert it"