From d0d3b0136eff38268504c938e70b7cfca5be7ccf Mon Sep 17 00:00:00 2001 From: Jacob Floyd Date: Thu, 12 Mar 2020 17:43:43 -0500 Subject: [PATCH] Add timezone aware snap modifiers This allows for modifications in the given timezone. ie, snapping to the beginning of the day with @d uses midnight in the given timezone instead of in UTC. As usual, the maya object returned is back in UTC, only the modifications happen in the requested timezone. --- README.rst | 5 +++++ src/maya/core.py | 11 +++++++++++ tests/test_maya.py | 20 ++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/README.rst b/README.rst index 8e7e1c8..b6f03f4 100644 --- a/README.rst +++ b/README.rst @@ -92,6 +92,11 @@ Behold, datetimes for humans! >>> dt.snap('@d+3h').rfc2822() 'Mon, 21 Feb 1994 03:00:00 GMT' + # snap modifiers within a timezone + >>> dt = maya.when('Mon, 21 Feb 1994 21:21:42 GMT') + >>> dt.snap_tz('+3h@d', 'Australia/Perth').rfc2822() + 'Mon, 21 Feb 1994 16:00:00 GMT' + ☤ Advanced Usage of Maya ------------------------ diff --git a/src/maya/core.py b/src/maya/core.py index bcdb90f..1b5eb8d 100644 --- a/src/maya/core.py +++ b/src/maya/core.py @@ -153,6 +153,17 @@ class MayaDT(object): """ return self.from_datetime(snaptime.snap(self.datetime(), instruction)) + def snap_tz(self, instruction, in_timezone): + """ + Returns a new MayaDT object modified by the given instruction. + The modifications happen in the given timezone. + + Powered by snaptime. See https://github.com/zartstrom/snaptime + for a complete documentation about the snaptime instructions. + """ + dt_tz = self.datetime(to_timezone=in_timezone) + return self.from_datetime(snaptime.snap_tz(dt_tz, instruction, dt_tz.tzinfo)) + # Timezone Crap # ------------- @property diff --git a/tests/test_maya.py b/tests/test_maya.py index ca8ffc5..a528309 100644 --- a/tests/test_maya.py +++ b/tests/test_maya.py @@ -383,3 +383,23 @@ def test_snaptime(when_str, snap_str, expected_when): dt = dt.snap(snap_str) # then assert dt == maya.when(expected_when) + + +@pytest.mark.parametrize( + "when_str,snap_str,timezone,expected_when", + [ + ( + "Mon, 21 Feb 1994 21:21:42 GMT", + "@d", + "Australia/Perth", + "Mon, 21 Feb 1994 16:00:00 GMT", + ) + ], +) +def test_snaptime_tz(when_str, snap_str, timezone, expected_when): + # given + dt = maya.when(when_str) + # when + dt = dt.snap_tz(snap_str, timezone) + # then + assert dt == maya.when(expected_when)