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. The problem is, when reading it it comes back as a string, but I need to reconstruct the original datetime object. How do I do this?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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:
Put the type I wanted into the query - and for datetime, it's not actually "datetime", but "timestamp":
If I pass in "datetime" instead it's silently ignored and I still get a string back. Same if I omit the quotes.
If you declare your column with a type of timestamp, you're in clover:
See? both int (for a column declared integer) and datetime (for a column declared timestamp) survive the round-trip with the type intact.
Note: In Python3, I had to change the SQL to something like:
SELECT jobid, startedTime as "st [timestamp]" FROM job
(I had to explicitly name the column.)