Refactor get_delta_from_subject() method
Refactors the get_delta_from_subject() method for a few benefits: * Checks type more idiomatically (using isinstance instead of type) * Raise a TypeError if passed a type that isn't able to be handled * Return immediately if passed a timedelta, so the rest of the method doesn't need to be inside an else block
This commit is contained in:
parent
b2f6af9d70
commit
217a7fbe61
1 changed files with 20 additions and 11 deletions
31
ago.py
31
ago.py
|
|
@ -4,18 +4,27 @@ units = ("year", "day", "hour", "minute", "second", "millisecond", "microsecond"
|
|||
|
||||
|
||||
def get_delta_from_subject(subject):
|
||||
subject_type = type(subject)
|
||||
if subject_type is timedelta:
|
||||
delta = subject
|
||||
"""Convert the subject to a timedelta and return it."""
|
||||
if isinstance(subject, timedelta):
|
||||
return subject
|
||||
|
||||
if isinstance(subject, datetime):
|
||||
dt = subject
|
||||
else:
|
||||
if subject_type is int or subject_type is float:
|
||||
dt = datetime.fromtimestamp(float(subject))
|
||||
else:
|
||||
# assume subject is a datetime object and strip timezone data.
|
||||
dt = subject.replace(tzinfo=None)
|
||||
# finally, create a timedelta from datetime.
|
||||
delta = datetime.now() - dt
|
||||
return delta
|
||||
# if it's not a datetime, assume it's a unix timestamp
|
||||
try:
|
||||
subject = float(subject)
|
||||
except ValueError:
|
||||
# some unknown type that couldn't be converted to a float
|
||||
raise TypeError("Unsupported subject type")
|
||||
|
||||
dt = datetime.fromtimestamp(subject)
|
||||
|
||||
# strip timezone data
|
||||
dt = dt.replace(tzinfo=None)
|
||||
|
||||
# finally, return a timedelta from the datetime
|
||||
return datetime.now() - dt
|
||||
|
||||
|
||||
def delta2dict(delta):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue