Skip to content

Commit

Permalink
Add datetime.timezone.utc tzinfo to Timestamp.datetime
Browse files Browse the repository at this point in the history
  • Loading branch information
ahawker committed Aug 8, 2020
1 parent bedc21c commit 88e725f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
12 changes: 12 additions & 0 deletions tests/test_bugs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Tests for validating reported bugs have been fixed.
"""
import copy
import datetime

import pytest

Expand Down Expand Up @@ -47,3 +48,14 @@ def test_github_issue_452():
"""
result = copy.deepcopy(api.new())
assert result is not None


def test_github_issue_463():
"""
Assert that :meth:`~ulid.ulid.Timestamp.datetime` returns the value as
a :class:`~datetime.datetime` instance that is UTC aware.
Issue: https://github.com/ahawker/ulid/issues/463
"""
instance = api.new()
assert instance.timestamp().datetime.tzinfo == datetime.timezone.utc
7 changes: 4 additions & 3 deletions tests/test_ulid.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,14 +322,15 @@ def test_timestamp_coverts_bytes_to_unix_time_seconds():
assert timestamp.timestamp == now_ms / 1000.0


def test_timestamp_converts_to_datetime():
def test_timestamp_converts_to_utc_aware_datetime():
"""
Assert that :meth:`~ulid.ulid.Timestamp.datetime` returns the value as
a :class:`~datetime.dateime` instance.
a :class:`~datetime.datetime` instance that is UTC aware.
"""
now_ms = int(time.time()) * 1000
timezone = datetime.timezone.utc
timestamp = ulid.Timestamp(now_ms.to_bytes(6, byteorder='big'))
assert timestamp.datetime == datetime.datetime.utcfromtimestamp(now_ms / 1000.0)
assert timestamp.datetime == datetime.datetime.utcfromtimestamp(now_ms / 1000.0).replace(tzinfo=timezone)


def test_ulid_timestamp_returns_instance(valid_bytes_128):
Expand Down
8 changes: 6 additions & 2 deletions ulid/ulid.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,12 @@ def datetime(self) -> hints.Datetime:
:return: Timestamp in datetime form.
:rtype: :class:`~datetime.datetime`
"""
mills = self.int
return datetime.datetime.utcfromtimestamp(mills // 1000.0).replace(microsecond=mills % 1000 * 1000)
milli = self.int
micro = milli % 1000 * 1000
sec = milli // 1000.0
timezone = datetime.timezone.utc

return datetime.datetime.utcfromtimestamp(sec).replace(microsecond=micro, tzinfo=timezone)


class Randomness(MemoryView):
Expand Down

0 comments on commit 88e725f

Please sign in to comment.