Skip to content

Commit b3a0a27

Browse files
committed
Merge pull request #2430 from Polyconseil/fbochu/timedelta-json-serialiser-python26-support
Fix timedelta JSON serialization on Python 2.6.
2 parents 4f27b96 + 5484d57 commit b3a0a27

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

rest_framework/compat.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ def unicode_to_repr(value):
3333
return value
3434

3535

36+
def total_seconds(timedelta):
37+
# TimeDelta.total_seconds() is only available in Python 2.7
38+
if hasattr(timedelta, 'total_seconds'):
39+
return timedelta.total_seconds()
40+
else:
41+
return (timedelta.days * 86400.0) + float(timedelta.seconds) + (timedelta.microseconds / 1000000.0)
42+
43+
3644
# OrderedDict only available in Python 2.7.
3745
# This will always be the case in Django 1.7 and above, as these versions
3846
# no longer support Python 2.6.

rest_framework/utils/encoders.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from django.utils import six, timezone
77
from django.utils.encoding import force_text
88
from django.utils.functional import Promise
9-
from rest_framework.compat import OrderedDict
9+
from rest_framework.compat import OrderedDict, total_seconds
1010
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
1111
import datetime
1212
import decimal
@@ -41,7 +41,7 @@ def default(self, obj):
4141
representation = representation[:12]
4242
return representation
4343
elif isinstance(obj, datetime.timedelta):
44-
return six.text_type(obj.total_seconds())
44+
return six.text_type(total_seconds(obj))
4545
elif isinstance(obj, decimal.Decimal):
4646
# Serializers will coerce decimals to strings by default.
4747
return float(obj)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy