【发布时间】:2018-01-04 18:41:24
【问题描述】:
在提出问题之前,我尝试了不同的方法,但都没有奏效。
我尝试使用 datetime.strptime 和 dateutil,但都没有工作,或者我做错了。 我什至尝试将日期拆分为 y、m、d 变量并更改为整数,然后尝试将所有 3 个变量加在一起以获得完整的日期变量。
我需要如何更新日期部分的编码,以便我可以从第二个/第三个/等读取和插入值。没有错误的列?
我在 Excel 日期和更改为 postgres 日期时遇到问题。 (Excel 中的日期字段有日期和时间。我只需要日期部分。)我正在使用 xlrd 读取日期列并将日期更改为我需要并插入的日期,但是一旦我添加另一列来读取和插入,我收到代码问题。
import psycopg2
import xlrd
import datetime
#Tried from datetime import datetime
try:
conn = psycopg2.connect(user = '', password = '', host =’’, database =’’, port = 0000)
mycursor = conn.cursor()
print('DB connection open')
print('Running SQL query')
#Open the excel
book = xlrd.open_workbook('name.xlsx')
#Open the workbook sheet
sheet = book.sheet_by_name('Date')
query = """INSERT INTO table_name(
date,
second_column
)
VALUES(
%s,
%s)"""
for r in range(1, sheet.nrows):
db_date = year_date = []
date = sheet.cell(r, 0).value
#Changing Excel date from m/d/y to y-m-d
date_mode = datetime.datetime(*xlrd.xldate_as_tuple(review_date, book.datemode))
start_date_full = date_mode
split_start_date_full = str(start_date_full)
#Splitting date to remove the time portion
split_start_date_full = split_start_date_full.split(" ")
#Adding the date to a list
year_date = split_start_date_full[0]
db_date.append((year_date))
#Assign values to each row
values = (
db_date,
second_column
)
mycursor.execute(query, values)
#Commit to the DB. Close the mycursor and conn.
mycursor.close()
conn.commit()
conn.close()
print('''All done!''')
except Exception as e:
#making sure cursor and conn is closed if I hit the except
mycursor.close()
conn.close()
print(e)
错误/结果: 如果我只调用日期列,插入没问题 第二个日期值只是 postgres db 表中的一个日期列,它根据插入行的时间插入日期。
>>>
================================ RESTART ================================
>>>
DB connection open
Running SQL query
(9616, datetime.date(2017, 12, 6), None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, datetime.date(2018, 1, 4))
All done!
I receive text error when I call a second/third/etc. columns
>>>
================================ RESTART ================================
>>>
DB connection open
Running SQL query
column "review_date" is of type date but expression is of type text[]
LINE 6: ARRAY['2017-12-06'],
^
HINT: You will need to rewrite or cast the expression.
>>>
【问题讨论】:
-
抱歉,我确实忘记在 for 循环中添加代码,以便从 Excel 中读取第二列。这将是日期的所有代码之后。 second_column = sheet.cell(r, 1).value
-
我想出了如何使这项工作(我是 Python 编码的新手,我会在我去的时候弄清楚。如果这是有道理的。我假设我需要添加我的答案作为答案。如果我错了,没关系。)
标签: python-3.x datetime postgresql-9.1 xlrd python-datetime