Skip to content

Commit

Permalink
Add function for converting milliseconds timestamp to datetime (#461)
Browse files Browse the repository at this point in the history
  • Loading branch information
bradengroom authored Aug 27, 2020
1 parent 15811b3 commit b5a6b7f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
5 changes: 5 additions & 0 deletions baseplate/lib/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/lib/datetime_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down

0 comments on commit b5a6b7f

Please sign in to comment.