Skip to content

Commit

Permalink
Add as_datetime method to DatetimeUs
Browse files Browse the repository at this point in the history
This method can be used to explicitly convert a `DatetimeUs` instance to
a `datetime` instance that can be used somewhere where instances of the
subclass are not accepted (such as pydantic).

Signed-off-by: Bernát Gábor <[email protected]>
  • Loading branch information
gaborbernat authored and godlygeek committed Jan 15, 2025
1 parent d36da37 commit f87217b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions comdb2/_cdb2_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ def replace(self, *args, **kwargs):
dt = super().replace(*args, **kwargs)
return self.fromdatetime(dt)

def as_datetime(self) -> datetime.datetime:
"""Return a `datetime` representation."""
return datetime.datetime(
year=self.year,
day=self.day,
month=self.month,
hour=self.hour,
minute=self.minute,
second=self.second,
microsecond=self.microsecond,
tzinfo=self.tzinfo,
fold=self.fold,
)


class ColumnType(enum.IntEnum):
"""This enum represents all known Comdb2 column types.
Expand Down
14 changes: 14 additions & 0 deletions tests/test_cdb2_datetimeus.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,20 @@ def test_datetimeus_astimezone():
assert type(dtu.astimezone(pytz.utc)) == cdb2.DatetimeUs


def test_datetimeus_as_datetime_naive():
dtu = cdb2.DatetimeUs.fromtimestamp(time.time())
dt = dtu.as_datetime()
assert type(dt) == datetime.datetime
assert dt == dtu


def test_datetimeus_as_datetime_with_tz():
dtu = cdb2.DatetimeUs.fromtimestamp(time.time(), tz=pytz.UTC)
dt = dtu.as_datetime()
assert type(dt) == datetime.datetime
assert dt == dtu


def test_datetimeus_type_stickiness():
def check(obj):
assert isinstance(obj, cdb2.DatetimeUs)
Expand Down

0 comments on commit f87217b

Please sign in to comment.