sqlite3中的Python日期时间
发布时间:2020-12-12 18:54:02 所属栏目:百科 来源:网络整理
导读:我在 Python 2.7中对sqlite3 datetime对象有一个奇怪的问题.运行此示例: import sqlite3import datetimecon = sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)cur = con.cursor()cur.execute("create table test
我在
Python 2.7中对sqlite3 datetime对象有一个奇怪的问题.运行此示例:
import sqlite3 import datetime con = sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) cur = con.cursor() cur.execute("create table test(d date,ts timestamp)") today = datetime.date.today() now = datetime.datetime.now() cur.execute("insert into test(d,ts) values (?,?)",(today,now)) cur.execute("select d,ts from test") row = cur.fetchone() print today,"=>",row[0],type(row[0]) print now,row[1],type(row[1]) cur.execute('select current_date as "d [date]",current_timestamp as "ts [timestamp]"') row = cur.fetchone() print today,type(row[1]) 给我这个输出: 2012-02-10 => 2012-02-10 <type 'datetime.date'> 2012-02-10 08:17:10.222291 => 2012-02-10 08:17:10.222291 <type 'datetime.datetime'> 2012-02-10 => 2012-02-09 <type 'datetime.date'> 2012-02-10 08:17:10.222291 => 2012-02-09 19:17:10 <type 'datetime.datetime'> 使用PARSE_COLNAMES方法时重试的日期时间似乎是错误的.这是为什么? 请注意,此示例来自Python docs 解决方法从您显示的输出中,您看起来像是在新西兰时区(UTC-12或UTC-11,观察到夏令时).问题是PARSE_COLNAMES如何将转换器用于python类型 – 一个是UTC,一个是使用可用于本地时间的时区信息(是的,我称之为转换器中的错误).请参阅下面我用于股票价格数据的适配器,以便为我知道的时区一致地转换数据(您可以调整它以匹配您的时区,或添加一些代码来调整检测到的时区): def adapt_datetime(dt): # Get the datetime for the POSIX epoch. epoch = datetime.datetime.utcfromtimestamp(0.0) elapsedtime = dt - epoch # Calculate the number of milliseconds. seconds = float(elapsedtime.days)*24.*60.*60. + float(elapsedtime.seconds) + float(elapsedtime.microseconds)/1000000.0 return seconds def convert_datetime(tf): # Note: strange math is used to account for daylight savings time and # times in the Eastern (US) time zone (e.g. EDT) tf = float(tf) edt_adjustment = 6 * 60. * 60. if time.localtime(tf).tm_isdst: edt_adjustment = 5 * 60. * 60. return datetime.datetime.fromtimestamp(tf+edt_adjustment) sqlite3.register_adapter(datetime.datetime,adapt_datetime) sqlite3.register_converter("datetime",convert_datetime) 您可以在github上的this bit of code中看到所有这些. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |