从datetime中删除时间并使用Python插入db表

时间:2018-01-04 18:41:25

标签: python-3.x datetime postgresql-9.1 xlrd python-datetime

在提出问题之前,我尝试了不同的方式而没有工作。

我尝试使用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.
>>> 

1 个答案:

答案 0 :(得分:0)

我采取的步骤:

  1. 我拆分year_date并输入year_date_full变量。

  2. 我为年,月和日创建了一个变量并转换为int的full_date

  3. 然后我将年+ - +月+ - +天合并到自己的变量中,并将该变量称为需要插入数据库表的值。

  4. for r in range(1, sheet.nrows):
        db_date = year_date = []
        #Date Column A
        date = sheet.cell(r, 0).value
        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)
        split_start_date_full = split_start_date_full.split(" ")
        year_date = split_start_date_full[0]
        time_date = split_start_date_full[1]
        #Split year_date '-' and put each section into its own variable
        year_date_full = year_date.split('-')
        start_year = year_date_full[0]
        start_month = year_date_full[1]
        start_day = year_date_full[2]
        #Turn str to a int for year, month, day
        full_date = (int(start_year),int(start_month),int(start_day))
        #created a new variable to hold the full year and '-'
        full_date_new = (start_year+'-'+start_month+'-'+start_day)
        #Second Column - Column B
        second_column = sheet.cell(r, 1).value
    

    插入结果:

    >>> ================================ RESTART ================================
    >>> 
    DB connection open
    Running SQL query
    (12621, **datetime.date(2017, 12, 6)**, None, None, None, None, None, None, None, None, None, None, None, None, **False**, None, None, datetime.date(2018, 1, 5))
    All done!
    >>>