How to handle datetime type in python sqlite3

I will show you how to handle datetime type (pseudo) in python standard library sqlite3.

There is no so-called date type (datetime type) in SQLite3, From the Python side, you can make SQLite behave as if it has a datetime type.

Code for the time being

With this kind of feeling

import sqlite3
import datetime

#Open the DB. Enable the conforming function / conversion function.
conn = sqlite3.connect(':memory:', 
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)

# "TIMESTAMP"Use the converter function as it is for "DATETIME"
sqlite3.dbapi2.converters['DATETIME'] = sqlite3.dbapi2.converters['TIMESTAMP']

#Cursor generation
cur = conn.cursor()

#Create a table with a column named datetime
cur.execute("create table mytable(comment text, updated datetime);"

#Try to input the character string expression and datetime in the datetime column respectively.
cur.executemany("insert into mytable(comment, updated) value (?,?)",
        [["text_formated.", "2014-01-02 23:45:00"],
        ["datetime_class.", datetime.datetime(2014,3,4, 12,34,56)]])


ret = cur.execute("select * from mytable;")

for row in ret.fetchall():
  print "'%s'" % row[0], row[1], type(row[1])

##Like this ↓, the column declared as datetime returns the datetime type.
# text_formated. 2014-01-02 23:45:00 <type 'datetime.datetime'>
# datetime_class. 2014-03-04 12:34:56 <type 'datetime.datetime'>

The datetime type looks only when viewed from Python, and the actual data format stored in the SQLite database is "2014-01-02 23:45:00" or "2014-03-04 12:34:56" It's just ** string data **.

In fact, in the python standard library sqlite3 / dbapi2.py, a" converter function "that makes the SQL type name" timestamp "the Python datetime is predefined.

How it works

This automatic conversion behavior is enabled by specifying detect_types = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES when doingsqlite3.connect ().

The list of converter functions is in sqlite3.dbapi2.converters, so Register the converter function for the already registered type name TIMESTAMP as it is for DATETIME, such as sqlite3.dbapi2.converters ['DATETIME'] = sqlite3.dbapi2.converters ['TIMESTAMP'] To do.

The above only describes datetime.datetime (YYYY, MM, DD, hh, mm, ss) [Python]-> "YYYY-MM-DD hh: mm: ss" [sqlite3]. Then where is the reverse pattern of the above "YYYY-MM-DD hh: mm: ss" [sqlite3]-> datetime.datetime (YYYY, MM, DD, hh, mm, ss) [Python]? I will omit the story. Roughly speaking, the "adapter function" that is input as a character string to SQLite when datetime is thrown is predefined in sqlite3 / dbapi2.py.

For more information, read 11.13.5.4. Default matching and conversion functions --SQLite in the Python Standard Library Reference. is.

Recommended Posts

How to handle datetime type in python sqlite3
How to use SQLite in Python
How to handle Japanese in Python
How to develop in Python
How to handle JSON in Ruby, Python, JavaScript, PHP
[Python] How to do PCA in Python
How to handle session in SQLAlchemy
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
Sqlite in python
How to access environment variables in Python
How to dynamically define variables in Python
How to do R chartr () in Python
[Itertools.permutations] How to put permutations in Python
How to work with BigQuery in Python
How to get a stacktrace in python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
How to handle consecutive values in MySQL
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to display Hello world in python
How to use is and == in Python
How to write Ruby to_s in Python
Timezone specification when converting a string to datetime type in python
How to use the C library in Python
How to receive command line arguments in Python
[Python] How to use two types of type ()
How to clear tuples in a list (Python)
How to embed a variable in a python string
How to implement Discord Slash Command in Python
Summary of how to import files in Python 3
How to simplify restricted polynomial fit in python
How to use Python Image Library in python3 series
How to implement shared memory in Python (mmap.mmap)
How to create a JSON file in Python
How to install python
Summary of how to use MNIST in Python
[Introduction to Python] How to handle JSON format data
How to specify TLS version in python requests
How to handle Linux commands well from Python
Use cryptography module to handle OpenSSL in Python
How to notify a Discord channel in Python
How to get dictionary type elements of Python 2.7
How to get the files in the [Python] folder
How to use tkinter with python in pyenv
Handle Parquet in Python
How to run Leap Motion in non-Apple Python
[Python] How to draw a histogram in Matplotlib
How to output "Ketsumaimo" as standard output in Python
[Python] How to handle Japanese characters with openCV
How to make Python Interpreter changes in Pycharm
[Python] How to compare datetime with timezone added
How to plot autocorrelation and partial autocorrelation in python
How to remove duplicate elements in Python3 list
20th Offline Real-time How to Write Problems in Python