【问题标题】:Removing time from datetime and insert into db table using Python从 datetime 中删除时间并使用 Python 插入到 db 表中
【发布时间】: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


【解决方案1】:

我采取的步骤:

  1. 我将 year_date 拆分并放入 year_date_full 变量中。

  2. 我为年月日创建了一个变量,变成了int的full_date

  3. 然后我将year+-+month+-+day组合成自己的变量,并将该变量称为需要插入db表的值。


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!
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2017-12-11
    • 1970-01-01
    • 2010-11-26
    • 2013-07-15
    • 2014-09-07
    相关资源
    最近更新 更多