Skip to content

Commit

Permalink
Improve parsing to datetime and add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
JonnyWong16 committed Aug 2, 2023
1 parent 61c805f commit 73794a0
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions plexapi/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
import warnings
import zipfile
from collections import deque
from datetime import datetime
from datetime import datetime, timedelta, timezone
from getpass import getpass
from threading import Event, Thread
from urllib.parse import quote
from requests.status_codes import _codes as codes

import requests
from requests.status_codes import _codes as codes

from plexapi.exceptions import BadRequest, NotFound, Unauthorized

Expand Down Expand Up @@ -313,19 +313,22 @@ def toDatetime(value, format=None):
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str).
"""
if value and value is not None:
if value is not None:
if format:
try:
value = datetime.strptime(value, format)
return datetime.strptime(value, format)
except ValueError:
log.info('Failed to parse %s to datetime, defaulting to None', value)
log.info('Failed to parse "%s" to datetime as format "%s", defaulting to None', value, format)
return None
else:
# https://bugs.python.org/issue30684
# And platform support for before epoch seems to be flaky.
# Also limit to max 32-bit integer
value = min(max(int(value), 86400), 2**31 - 1)
value = datetime.fromtimestamp(int(value))
try:
return (datetime.fromtimestamp(0, tz=timezone.utc) + timedelta(seconds=int(value))).replace(tzinfo=None)
except ValueError:
log.info('Failed to parse "%s" to datetime as timestamp, defaulting to None', value)
return None
except OverflowError:
log.info('Failed to parse "%s" to datetime as timestamp (out-of-bounds), defaulting to None', value)
return None
return value


Expand Down

0 comments on commit 73794a0

Please sign in to comment.