首页 > 解决方案 > 为什么我的日期时间对象被转换为 Unicode

问题描述

我编写了一个程序,它从 SQL 表中挑选出相关信息,并将该信息呈现在 Pandas DataFrame 中。我正在尝试创建自己的表以进行测试,但 DataFrame 正在将我的 Datetime 对象转换为 Unicode。

以下代码构建表:

def launcher():
    curr_date = datetime.datetime.now().date()
    conn = db = sqlite3.Connection("test.db")
    db.execute("CREATE TABLE test(begin_ts, process_name, count, name)")

    values = OrderedDict()
    values[datetime.datetime.strptime('{0} 07:00:00'.format(curr_date), DATE_FORMAT)] = 10
    values[datetime.datetime.strptime('{0} 10:00:00'.format(curr_date), DATE_FORMAT)] = 123456
    values[datetime.datetime.strptime('{0} 13:00:00'.format(curr_date), DATE_FORMAT)] = 75682
    values[datetime.datetime.strptime('{0} 16:00:00'.format(curr_date), DATE_FORMAT)] = 789545
    values[datetime.datetime.strptime('{0} 20:00:00'.format(curr_date), DATE_FORMAT)] = 25469

    test_values = []
    for x in range(1, 4):
        for time, tps in values.items():
            print("Time is of type {0} in the table".format(type(time)))
            test_values.append((time, 'matching_{0}_gw'.format(x), tps))
            values[time] = tps + 30

    for elem in test_values:
        db.execute("INSERT INTO test VALUES (?, ?, ?, 'raw_msg_count')", [elem[0], elem[1], elem[2]])

    print(db.execute("SELECT * FROM test").fetchall())

    return conn

以下代码是DataFrame代码:

df = pd.read_sql_query(self.query(), database)  # self.query() is just a query that picks out the relevant information
for elem in df.begin_ts:
        print("Time is of type {0} in the DataFrame".format(type(elem))            
df.begin_ts = df.begin_ts.dt.tz_convert('US/Eastern')

输出:

Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'datetime.datetime'> in the table
Time is of type <type 'unicode'> in the DataFrame
Time is of type <type 'unicode'> in the DataFrame
Time is of type <type 'unicode'> in the DataFrame

我在 DataFrame 代码的最后一行收到以下错误:

属性错误:只能将 .dt 访问器与 datetimelike 值一起使用

*编辑:通过将列作为 read_sql_query() 中的 parse_dates 参数传递来解决 *

标签: pythonpandassqlitedataframe

解决方案


推荐阅读