How to read datetime back from sqlite as a datetime instead of string in Python?

前端 未结 3 2072
忘掉有多难
忘掉有多难 2020-11-28 03:56

I\'m using the sqlite3 module in Python 2.6.4 to store a datetime in a SQLite database. Inserting it is very easy, because sqlite automatically converts the date to a string

3条回答
  •  情歌与酒
    2020-11-28 04:36

    If you declare your column with a type of timestamp, you're in clover:

    >>> db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
    >>> c = db.cursor()
    >>> c.execute('create table foo (bar integer, baz timestamp)')
    
    >>> c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
    
    >>> c.execute('select * from foo')
    
    >>> c.fetchall()
    [(23, datetime.datetime(2009, 12, 1, 19, 31, 1, 40113))]
    

    See? both int (for a column declared integer) and datetime (for a column declared timestamp) survive the round-trip with the type intact.

提交回复
热议问题