From 1b7429c3e1711da08be379b646097d7421ecdbc5 Mon Sep 17 00:00:00 2001 From: Pi Delport Date: Wed, 22 Aug 2018 18:51:43 +0200 Subject: [PATCH] (Python 2 compatibility for datetime.timestamp) --- analytical/templatetags/intercom.py | 12 ++++++++++-- analytical/tests/test_tag_intercom.py | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/analytical/templatetags/intercom.py b/analytical/templatetags/intercom.py index 92badec..888a0ab 100644 --- a/analytical/templatetags/intercom.py +++ b/analytical/templatetags/intercom.py @@ -7,6 +7,7 @@ from __future__ import absolute_import import hashlib import hmac import json +import sys import time import re @@ -28,6 +29,14 @@ TRACKING_CODE = """ register = Library() +def _timestamp(when): # type: (datetime) -> float + """ + Python 2 compatibility for `datetime.timestamp()`. + """ + return (time.mktime(when.timetuple()) if sys.version_info < (3,) else + when.timestamp()) + + def _hashable_bytes(data): # type: (AnyStr) -> bytes """ Coerce strings to hashable bytes. @@ -100,8 +109,7 @@ class IntercomNode(Node): params.setdefault('user_id', user.pk) - params['created_at'] = int(time.mktime( - user.date_joined.timetuple())) + params['created_at'] = int(_timestamp(user.date_joined)) else: params['created_at'] = None diff --git a/analytical/tests/test_tag_intercom.py b/analytical/tests/test_tag_intercom.py index 03cc47f..2085fcb 100644 --- a/analytical/tests/test_tag_intercom.py +++ b/analytical/tests/test_tag_intercom.py @@ -9,7 +9,7 @@ from django.http import HttpRequest from django.template import Context from django.test.utils import override_settings -from analytical.templatetags.intercom import IntercomNode, intercom_user_hash +from analytical.templatetags.intercom import IntercomNode, intercom_user_hash, _timestamp from analytical.tests.utils import TagTestCase from analytical.utils import AnalyticalException @@ -123,7 +123,7 @@ class IntercomTagTestCase(TagTestCase): ) # type: User attrs = IntercomNode()._get_custom_attrs(Context({'user': user})) self.assertEqual({ - 'created_at': int(user.date_joined.timestamp()), + 'created_at': int(_timestamp(user.date_joined)), 'email': 'test@example.com', 'name': '', 'user_hash': intercom_user_hash(str(user.pk)),