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

前端 未结 3 2070
忘掉有多难
忘掉有多难 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:44

    It turns out that sqlite3 can do this and it's even documented, kind of - but it's pretty easy to miss or misunderstand.

    What I had to do is:

    • Pass the sqlite3.PARSE_COLNAMES option in the .connect() call, eg.
    conn = sqlite3.connect(dbFilePath, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    
    • Put the type I wanted into the query - and for datetime, it's not actually "datetime", but "timestamp":

      sql = 'SELECT jobid, startedTime as "[timestamp]" FROM job'
      
      cursor = conn.cursor()
      try:
          cursor.execute(sql)
          return cursor.fetchall()
      finally:
          cursor.close()
      

    If I pass in "datetime" instead it's silently ignored and I still get a string back. Same if I omit the quotes.

提交回复
热议问题