Skip to content

Commit 5324893

Browse files
gh-99392: Fix sqlite3 converter recipes (GH-99393)
(cherry picked from commit dfc1b17) Co-authored-by: naglis <[email protected]>
1 parent 535027f commit 5324893

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

Doc/library/sqlite3.rst

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1683,20 +1683,39 @@ This section shows recipes for common adapters and converters.
16831683

16841684
def convert_date(val):
16851685
"""Convert ISO 8601 date to datetime.date object."""
1686-
return datetime.date.fromisoformat(val)
1686+
return datetime.date.fromisoformat(val.decode())
16871687

16881688
def convert_datetime(val):
16891689
"""Convert ISO 8601 datetime to datetime.datetime object."""
1690-
return datetime.datetime.fromisoformat(val)
1690+
return datetime.datetime.fromisoformat(val.decode())
16911691

16921692
def convert_timestamp(val):
16931693
"""Convert Unix epoch timestamp to datetime.datetime object."""
1694-
return datetime.datetime.fromtimestamp(val)
1694+
return datetime.datetime.fromtimestamp(int(val))
16951695

16961696
sqlite3.register_converter("date", convert_date)
16971697
sqlite3.register_converter("datetime", convert_datetime)
16981698
sqlite3.register_converter("timestamp", convert_timestamp)
16991699

1700+
.. testcode::
1701+
:hide:
1702+
1703+
dt = datetime.datetime(2019, 5, 18, 15, 17, 8, 123456)
1704+
1705+
assert adapt_date_iso(dt.date()) == "2019-05-18"
1706+
assert convert_date(b"2019-05-18") == dt.date()
1707+
1708+
assert adapt_datetime_iso(dt) == "2019-05-18T15:17:08.123456"
1709+
assert convert_datetime(b"2019-05-18T15:17:08.123456") == dt
1710+
1711+
# Using current time as fromtimestamp() returns local date/time.
1712+
# Droping microseconds as adapt_datetime_epoch truncates fractional second part.
1713+
now = datetime.datetime.now().replace(microsecond=0)
1714+
current_timestamp = int(now.timestamp())
1715+
1716+
assert adapt_datetime_epoch(now) == current_timestamp
1717+
assert convert_timestamp(str(current_timestamp).encode()) == now
1718+
17001719

17011720
.. _sqlite3-connection-shortcuts:
17021721

0 commit comments

Comments
 (0)