Language/Python
파이썬 sqlite3 사용하기 -3 : 컬럼에 자동 타임스탬프 찍기
jvvp512
2020. 7. 21. 17:25
728x90
Date And Time Functions
1. Overview SQLite supports five date and time functions as follows: date(timestring, modifier, modifier, ...) time(timestring, modifier, modifier, ...) datetime(timestring, modifier, modifier, ...) julianday(timestring, modifier, modifier, ...) strftime(f
www.sqlite.org
컬럼에 자동 타임스탬프 찍기
DEFAULT 키워드를 사용하면 데이터 삽입시 해당 컬럼에 설정한 값이 자동 삽입됩니다.
시간은 UTC(국제 표준시)와 KST(한국 표준시)가 있고 KST는 UTC보다 9시간 빠른 표준시(UTC+09:00)이다.
CURRENT_TIMESTAMP는 UTC 시간을 표시한다.
import sqlite3
conn = sqlite3.connect('blog.db')
cur = conn.cursor()
sql = '''CREATE TABLE color (id integer not null primary key autoincrement,
DATETIME DEFAULT CURRENT_TIMESTAMP,
name text not null,
rgb text)'''
cur.execute(sql)
colors = {
'red': '(255, 0, 0)',
'green': '(0, 255, 0)',
'blue': '(0, 0, 255)'
}
for k, v in colors.items():
sql = '''INSERT INTO color(name, rgb) VALUES ('{}', '{}')'''.format(k, v)
cur.execute(sql)
conn.commit()
sql = '''SELECT * from color'''
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
print(row)
conn.close()
(1, '2020-07-21 07:53:44', 'red', '(255, 0, 0)')
(2, '2020-07-21 07:53:44', 'green', '(0, 255, 0)')
(3, '2020-07-21 07:53:44', 'blue', '(0, 0, 255)')
우리나라 표준시(로컬시간)로 사용하려면
DATETIME('now', 'localtime')
sql = '''CREATE TABLE color (id integer not null primary key autoincrement,
timestamp DATETIME DEFAULT (DATETIME('now', 'localtime')),
name text not null,
rgb text)'''
(1, '2020-07-21 17:09:08', 'red', '(255, 0, 0)')
(2, '2020-07-21 17:09:08', 'green', '(0, 255, 0)')
(3, '2020-07-21 17:09:08', 'blue', '(0, 0, 255)')
문자열 포맷을 지정하고자하면
strftime('%Y%m%d_%H%M%S', DATETIME('now', 'localtime'))
sql = '''CREATE TABLE color (id integer not null primary key autoincrement,
timestamp DATETIME DEFAULT (strftime('%Y%m%d_%H%M%S', DATETIME('now', 'localtime'))),
name text not null,
rgb text)'''
(1, '20200721_171818', 'red', '(255, 0, 0)')
(2, '20200721_171818', 'green', '(0, 255, 0)')
(3, '20200721_171818', 'blue', '(0, 0, 255)')
strftime('%s', DATETIME('now', 'localtime'))
초로 반환합니다. int 형 타입인게 조금 특이합니다.
sql = '''CREATE TABLE color (id integer not null primary key autoincrement,
timestamp DATETIME DEFAULT (strftime('%s', DATETIME('now', 'localtime'))),
name text not null,
rgb text)'''
...
rows = cur.fetchall()
for row in rows:
print(row, type(row[1]))
(1, 1595352176, 'red', '(255, 0, 0)') <class 'int'>
(2, 1595352176, 'green', '(0, 255, 0)') <class 'int'>
(3, 1595352176, 'blue', '(0, 0, 255)') <class 'int'>