diff --git a/baseplate/lib/datetime.py b/baseplate/lib/datetime.py index aaa90c927..71a3e38a7 100644 --- a/baseplate/lib/datetime.py +++ b/baseplate/lib/datetime.py @@ -15,6 +15,11 @@ def datetime_to_epoch_seconds(dt: datetime) -> int: return datetime_to_epoch_milliseconds(dt) // 1000 +def epoch_milliseconds_to_datetime(ms: int) -> datetime: + """Convert epoch milliseconds to UTC datetime.""" + return datetime.utcfromtimestamp(ms / 1000).replace(tzinfo=timezone.utc) + + def epoch_seconds_to_datetime(sec: int) -> datetime: """Convert epoch seconds to UTC datetime.""" return datetime.utcfromtimestamp(sec).replace(tzinfo=timezone.utc) diff --git a/tests/unit/lib/datetime_tests.py b/tests/unit/lib/datetime_tests.py index bf75d02ca..db86b4b6a 100644 --- a/tests/unit/lib/datetime_tests.py +++ b/tests/unit/lib/datetime_tests.py @@ -7,6 +7,7 @@ from baseplate.lib.datetime import datetime_to_epoch_milliseconds from baseplate.lib.datetime import datetime_to_epoch_seconds +from baseplate.lib.datetime import epoch_milliseconds_to_datetime from baseplate.lib.datetime import epoch_seconds_to_datetime from baseplate.lib.datetime import get_utc_now @@ -20,6 +21,7 @@ def test_datetime_conversions(self): epoch_ms = datetime_to_epoch_milliseconds(EXAMPLE_DATETIME) self.assertEqual(EXAMPLE_DATETIME, epoch_seconds_to_datetime(epoch_sec)) self.assertEqual(epoch_sec, int(epoch_ms / 1000)) + self.assertEqual(EXAMPLE_DATETIME, epoch_milliseconds_to_datetime(epoch_ms)) def test_timezone_equivalence(self): pytz_datetime = EXAMPLE_DATETIME.replace(tzinfo=pytz.UTC)