将时间戳转换为to_date

时间:2018-11-18 16:59:03

标签: python pandas

我正在尝试构建一个桌面应用程序,以通过熊猫数据框从Excel生成SQL查询。我能够生成insert语句,但是我正在接收time_stamp格式的数据(其中列是日期),我想将其转换为to_date格式,请提出一种更好的方法。另外,建议使用相同的代码/相同的类型来生成选择/更新语句。 这是我的输入文件: Excel:
Excel

这是我的代码:-

from pandas import *
table_name="ADI"
file_name=pandas.read_excel('supermarke.xlsx')    

    def SQL_Insert(SOURCE, TARGET):
        sql_texts = []
        for index, row in SOURCE.iterrows():
            sql_texts.append(
                'INSERT INTO ' + TARGET + ' (' + str(', '.join(SOURCE.columns)) + ')   VALUES ' + str(tuple(row.values))+";")

        return ('\n'.join(sql_texts))
    print(SQL_Insert(file_name, table_name))**

结果是:-

INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (1, '3666 21st St', 'San Francisco', 'CA 94114', 'USA', 'Madeira', 8, Timestamp('2018-01-12 00:00:00'));
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (2, '735 Dolores St', 'San Francisco', 'CA 94119', 'USA', 'Bready Shop', 15, Timestamp('2018-01-12 00:00:00'));
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (3, '332 Hill St', 'San Francisco', 'California 94114', 'USA', 'Super River', 25, Timestamp('2018-01-12 00:00:00'));
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (4, '3995 23rd St', 'San Francisco', 'CA 94114', 'USA', "Ben's Shop", 10, Timestamp('2018-01-12 00:00:00'));

这是我所期望的:-

INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (1, '3666 21st St', 'San Francisco', 'CA 94114', 'USA', 'Madeira', 8,  TO_DATE('12/01/2018 00:00:00', 'MM/DD/YYYY HH24:MI:SS');
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (2, '735 Dolores St', 'San Francisco', 'CA 94119', 'USA', 'Bready Shop', 15, TO_DATE('12/01/2018 00:00:00', 'MM/DD/YYYY HH24:MI:SS');
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (3, '332 Hill St', 'San Francisco', 'California 94114', 'USA', 'Super River', 25,TO_DATE('12/01/2018 00:00:00', 'MM/DD/YYYY HH24:MI:SS');
INSERT INTO ADI (ID, Address, City, State, Country, Supermarket Name, Number of Employees, DATE)   VALUES (4, '3995 23rd St', 'San Francisco', 'CA 94114', 'USA', "Ben's Shop", 10, TO_DATE('12/01/2018 00:00:00', 'MM/DD/YYYY HH24:MI:SS');

请建议如何执行此操作,并且请勿建议以如下方式进行硬编码:-

df["DATE"] = df.DATE.dt.date

我正在构建一个应用程序,所以请建议如何以通用方式进行操作。

0 个答案:

没有答案