为什么我的Datetime对象被转换为Unicode

时间:2019-06-24 17:10:47

标签: python pandas sqlite dataframe

我编写了一个程序,该程序从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代码的最后一行中出现以下错误:

属性错误:只能使用具有类似datetime值的.dt访问器

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

0 个答案:

没有答案