Почему мой объект Datetime конвертируется в Unicode? - PullRequest
0 голосов
/ 24 июня 2019

Я написал программу, которая выбирает соответствующую информацию из таблицы SQL и представляет эту информацию в DataFrame Pandas. Я пытаюсь создать свою собственную таблицу для целей тестирования, но 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 со значениями типа datetime

* Редактировать: Разрешается путем передачи столбца в качестве параметра parse_dates в read_sql_query () *

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...