From 61362579f66ddffc7b03daa2e381588e84e88b72 Mon Sep 17 00:00:00 2001 From: Jad Chaar Date: Sun, 3 May 2020 06:02:01 -0400 Subject: [PATCH] Fix x formatting token on Python 2.7 (#781) * Fix bug with x token in formatter on Python 2.7 * Tweak Makefile to run tests before publishing --- Makefile | 2 +- arrow/formatter.py | 4 +++- tests/test_formatter.py | 13 +++++++------ 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 7c7f7379a..e89992c86 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,7 @@ clean: rm -rf dist build .egg .eggs arrow.egg-info rm -f ./**/*.pyc .coverage -publish: +publish: test rm -rf dist build .egg .eggs arrow.egg-info pip3 install -U setuptools twine wheel python3 setup.py sdist bdist_wheel diff --git a/arrow/formatter.py b/arrow/formatter.py index 2a76b3385..325c393f1 100644 --- a/arrow/formatter.py +++ b/arrow/formatter.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import +from __future__ import absolute_import, division import calendar import re @@ -98,9 +98,11 @@ def _format_token(self, dt, token): return str(int(dt.microsecond / 100000)) if token == "X": + # TODO: replace with a call to dt.timestamp() when we drop Python 2.7 return str(calendar.timegm(dt.utctimetuple())) if token == "x": + # TODO: replace with a call to dt.timestamp() when we drop Python 2.7 ts = calendar.timegm(dt.utctimetuple()) + (dt.microsecond / 1000000) return str(int(ts * 1000000)) diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 94ac44f03..24186a0aa 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -import time from datetime import datetime import pytest @@ -101,13 +100,15 @@ def test_sub_second(self): def test_timestamp(self): - timestamp = time.time() + timestamp = 1588437009.8952794 dt = datetime.utcfromtimestamp(timestamp) - assert self.formatter._format_token(dt, "X") == str(int(timestamp)) + expected = str(int(timestamp)) + assert self.formatter._format_token(dt, "X") == expected - # time.time() may return a float with greater than 6 digits of precision - rounded_ts = str(round(timestamp * 1000000)) - assert self.formatter._format_token(dt, "x") == rounded_ts.format("{f}") + # Must round because time.time() may return a float with greater + # than 6 digits of precision + expected = str(int(timestamp * 1000000)) + assert self.formatter._format_token(dt, "x") == expected def test_timezone(self):