简体   繁体   中英

Python csv_writer: Change the output format of a oracle date column

I have a table with a date column and want to format that column to DD.MM.YYYYY in a csv file but alter session does not effect the python csv_writer.

Is there a way to handle all date columns without using to_char in the sql code?

file_handle=open("test.csv","w")
csv_writer = csv.writer(file_handle,dialect="excel",lineterminator='\n',delimiter=';',quoting=csv.QUOTE_NONNUMERIC)
conn=cx_Oracle.connect(connectionstring)
cur = conn.cursor()

cur.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'DD.MM.YYYY HH24:MI:SS'")
cur.execute("select attr4,to_char(attr4,'DD.MM.YYYY') from aTable")
rows = cur.fetchmany(16000)

while len(rows) > 0:
    csv_writer.writerows(rows)
    rows = cur.fetchmany(16000)
cur.close()

result:

"1943-04-21 00:00:00";"21.04.1943"
"1955-12-22 00:00:00";"22.12.1955"
"1947-11-01 00:00:00";"01.11.1947"
"1960-01-07 00:00:00";"07.01.1960"
"1979-12-01 00:00:00";"01.12.1979"

The output you see comes from the fact the result of a query is converted to the corresponding python datatypes - thus the values of the first column are datetime objects, and the second - strings ( due to the to_char() cast you do in the query ). The NLS_DATE_FORMAT controls the output for just regular (user) clients.
Thus the output in the csv is just the default representation of the python's datetime ; if you want to output in a different form, you just need to change it.

As the query response is a list of tuples, you can't just change it in-place - it has to be copied and modified; alternatively, you could write it row by row, modified.

Here's just the write part with the 2nd approach:

import datetime

# the rest of your code

while len(rows) > 0:
    for row in rows:
        value = (row[0].strftime('%d.%m.%Y'), row[1])
        csv_writer.writerow(value)
    rows = cur.fetchmany(16000)

For reference, here's a short list with the python's strftime directives .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM