developer tip

Python에서 문자열 대신 datetime으로 sqlite에서 datetime을 다시 읽는 방법은 무엇입니까?

copycodes 2020. 11. 27. 08:21
반응형

Python에서 문자열 대신 datetime으로 sqlite에서 datetime을 다시 읽는 방법은 무엇입니까?


SQLite 데이터베이스에 날짜 시간을 저장하기 위해 Python 2.6.4에서 sqlite3 모듈을 사용하고 있습니다. sqlite는 자동으로 날짜를 문자열로 변환하기 때문에 삽입이 매우 쉽습니다. 문제는 그것을 읽을 때 문자열로 돌아 오지만 원래 datetime 객체를 재구성해야한다는 것입니다. 어떻게해야합니까?


타임 스탬프 유형으로 열을 선언하면 클로버 상태입니다.

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

보다? int (정수로 선언 된 열의 경우)와 datetime (열로 선언 된 타임 스탬프의 경우)은 모두 유형이 손상되지 않은 라운드 트립에서 유지됩니다.


sqlite3는 이것을 할 수 있고 심지어 문서화되어 있습니다 .하지만 놓치거나 오해하기가 꽤 쉽습니다.

내가해야 할 일은 :

  • 패스 sqlite3.PARSE_COLNAMES의 예 .connect () 호출에서 옵션을 선택합니다.
conn = sqlite3.connect(dbFilePath, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
  • 원하는 유형을 쿼리에 넣습니다. datetime의 경우 실제로 "datetime"이 아니라 "timestamp"입니다.

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

대신 "datetime"을 전달하면 자동으로 무시되고 여전히 문자열이 반환됩니다. 따옴표를 생략해도 동일합니다.


참고 : Python3에서는 SQL을 다음과 같이 변경해야했습니다.

SELECT jobid, startedTime as "st [timestamp]" FROM job

(열 이름을 명시 적으로 지정해야했습니다.)

참고 URL : https://stackoverflow.com/questions/1829872/how-to-read-datetime-back-from-sqlite-as-a-datetime-instead-of-string-in-python

반응형