在熊猫中将时间戳转换为to_date
Posted
技术标签:
【中文标题】在熊猫中将时间戳转换为to_date【英文标题】:Converting time stamp to to_date in pandas 【发布时间】:2019-04-26 20:41:35 【问题描述】:我正在为 sql 查询类型构建和应用程序,我能够生成它但接收时间戳格式的输出,请帮助将其转换为 to_date 格式。 这是我的代码:-
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');
请帮帮我
【问题讨论】:
快速修复:在您的循环中,首先使用strftime
构建日期字符串,然后使用str(tuple(row.values[:-1])) + custom_date_str + ";"
将其包含到字符串中。更大的修复:我建议不要手动构建 SQL 查询字符串,而是使用像 PyPika 这样的库。
@PeterLeimbigler,请详细说明,我没明白。谢谢
【参考方案1】:
如果您必须手动将 SQL 查询字符串拼接在一起,试试这个(未经测试,因为我没有您的数据):
import pandas as pd
table_name = 'ADI'
df = pandas.read_excel('supermarke.xlsx')
def SQL_Insert(SOURCE, TARGET):
sql_texts = []
for index, row in SOURCE.iterrows():
formatted_date = pd.to_datetime(row[-1]).strftime('%m/%d/%Y %H:%M:%S')
date_str = 'TO_DATE(\'\', \'MM/DD/YYYY HH24:MI:SS\')'.format(formatted_date)
sql_texts.append((
'INSERT INTO ' +
TARGET +
' (' +
str(', '.join(SOURCE.columns)) + ') VALUES ' +
str(tuple(row.values[:-1])) +
date_str +
';'))
return ('\n'.join(sql_texts))
print(SQL_Insert(df, table_name))
我建议不要手动构建查询字符串。这是一个已解决的问题。延伸阅读:How do I get a raw, compiled SQL query from a SQLAlchemy expression?
【讨论】:
我遇到以下错误:- formatted_date = row[-1].datetime.strptime('%m/%d/%Y %H:%M:%S') AttributeError: 'str ' 对象没有属性 'datetime' 试试我实际写的,是formatted_date = row[-1].strftime('%m/%d/%Y %H:%M:%S')
(不是.datetime
)
我尝试了同样的错误。 formatted_date = row[-1].strftime('%m/%d/%Y %H:%M:%S') AttributeError: 'str' object has no attribute 'strftime'
@adityasingh,那么您必须在日期列上运行 pd.to_datetime()
才能将其从字符串格式转换。我已经编辑了答案,但没有看到您的数据,我无法确定它是否会起作用。
仍然收到错误文件“C:\Users\adiec\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dateutil\parser_parser.py”,第 1356 行,在解析返回 DEFAULTPARSER.parse(timestr, **kwargs) 文件“C:\Users\adiec\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dateutil\parser_parser.py”,第 648 行,在parse raise ValueError("Unknown string format:", timestr) ValueError: ('Unknown string format:', 'null') Edited the question added input data以上是关于在熊猫中将时间戳转换为to_date的主要内容,如果未能解决你的问题,请参考以下文章