Skip to content

Commit 8aa161a

Browse files
committed
add sqlite datetime converter
1 parent df201ed commit 8aa161a

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

docs/tutorial/database.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ response is sent.
3737
:caption: ``flaskr/db.py``
3838
3939
import sqlite3
40+
from datetime import datetime
4041
4142
import click
4243
from flask import current_app, g
@@ -132,6 +133,11 @@ Add the Python functions that will run these SQL commands to the
132133
init_db()
133134
click.echo('Initialized the database.')
134135
136+
137+
sqlite3.register_converter(
138+
"timestamp", lambda v: datetime.fromisoformat(v.decode())
139+
)
140+
135141
:meth:`open_resource() <Flask.open_resource>` opens a file relative to
136142
the ``flaskr`` package, which is useful since you won't necessarily know
137143
where that location is when deploying the application later. ``get_db``
@@ -142,6 +148,10 @@ read from the file.
142148
that calls the ``init_db`` function and shows a success message to the
143149
user. You can read :doc:`/cli` to learn more about writing commands.
144150

151+
The call to :func:`sqlite3.register_converter` tells Python how to
152+
interpret timestamp values in the database. We convert the value to a
153+
:class:`datetime.datetime`.
154+
145155

146156
Register with the Application
147157
-----------------------------

examples/tutorial/flaskr/db.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import sqlite3
2+
from datetime import datetime
23

34
import click
45
from flask import current_app
@@ -44,6 +45,9 @@ def init_db_command():
4445
click.echo("Initialized the database.")
4546

4647

48+
sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode()))
49+
50+
4751
def init_app(app):
4852
"""Register database functions with the Flask app. This is called by
4953
the application factory.

0 commit comments

Comments
 (0)