1

I wanted to store a timestamp from Python in a sqlite3 database. For that I used this kind of code

from datetime import datetime, date, timedelta, time
import sqlite3
import os

def main():

    script_dir = os.path.abspath(os.path.dirname(__file__))
    database_file = os.path.join(script_dir, "sqlite.db")
    print(database_file)

    con = sqlite3.connect(database_file, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
    cur = con.cursor()
    cur.execute("""CREATE TABLE if not exists timstmp
        (DateCrt timestamp, DateSupp timestamp)"""
        )
    con.commit()

    cur.execute("SELECT * FROM timstmp")
    print(cur.fetchall())

    print(datetime.now())
    con = sqlite3.connect(database_file) , detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
    cur = con.cursor()
    cur.execute("INSERT into timstmp values (?, ?)", (datetime.now(), None))
    con.commit()

    cur.execute("SELECT * FROM timstmp")
    print(cur.fetchall())

    con.close()

if __name__ == '__main__':
    main()

It works well, I can store and retrieve values, they are timestamps in sqlite, and in Python too

But when executing, I have the warning

DeprecationWarning: The default datetime adapter is deprecated as of Python 3.12; see the sqlite3 documentation for suggested replacement recipes

So, I wanted to correct my code, and i added this lines of code (found in https://docs.python.org/3/library/sqlite3.html#sqlite3-adapter-converter-recipes)

def adapt_date_iso(val):
    """Adapt datetime.date to ISO 8601 date."""
    return val.isoformat()

def adapt_datetime_iso(val):
    """Adapt datetime.datetime to timezone-naive ISO 8601 date."""
    return val.isoformat()

def adapt_datetime_epoch(val):
    """Adapt datetime.datetime to Unix timestamp."""
    return int(val.timestamp())

sqlite3.register_adapter(date, adapt_date_iso)
sqlite3.register_adapter(datetime, adapt_datetime_iso)
sqlite3.register_adapter(datetime, adapt_datetime_epoch)

def convert_date(val):
    """Convert ISO 8601 date to datetime.date object."""
    return date.fromisoformat(val.decode())

def convert_datetime(val):
    """Convert ISO 8601 datetime to datetime.datetime object."""
    return datetime.fromisoformat(val.decode())

def convert_timestamp(val):
    """Convert Unix epoch timestamp to datetime.datetime object."""
    return datetime.fromtimestamp(int(val))

sqlite3.register_converter("date", convert_date)
sqlite3.register_converter("datetime", convert_datetime)
sqlite3.register_converter("timestamp", convert_timestamp)

It seems to work (from the python program), but the values stored in the database aren't timestamps anymore, they are integers (and now the precision is only one second).

Did I misunderstood the goal of the adapters and converters? Is this a way to have again a timestamp in the sqlite3 database, without potential problem with future versions of Python?

4
  • What do you mean by "timestamp", a Unix timestamp looks like an integer offset from epoch? Are you expecting a time string, in ISO8601 or other format, to be what's stored ? Commented Jun 30 at 17:27
  • 1
    why not save datetime.timestamp()? They are floats. Commented Jun 30 at 18:42
  • In fact, with your questions I understand that there's no native-format in sqlite for date and time value. There where no error when writing "timestamp" as the field type in CREATE TABLE, and viewing the data with the SQLITE viewer website made me think that it was working. So I'll transform the data explicitly now (numeric value or an ISO string). Thanks Commented Jun 30 at 18:55
  • FYI: A numeric value will represent the date at UTC timezone while and ISO string could contain other timezones 2025-06-30T16:02:40,362961306-05:00 Commented Jun 30 at 19:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.