getting date fields from oracle in correct format using Python and cx-oracle

浪子不回头ぞ 提交于 2019-12-12 05:09:34

问题


I am retrieving a load of data from one oracle database and then inserting it into another non linked database that is structurally the same.

I am doing it by doing:

select * from xxx where id = parameter

and

Select COLUMN_NAME from user_tab_columns where table_name=xxx

then with zip putting them in a dictionary as table_name:Data to build the insert from

Problem is it is returning the date fields as datetime.datetime(99, 12, 31, 0, 0). I need this as 31-dec-2999. How can I get it to return it like this or do I need to create a regex to do this?

I'm new to all this so if my method seems ridiculous feel free to say so and suggest a better method

Many thanks Adam


回答1:


The cx_Oracle database adapter is giving you datetime.datetime() objects. Use methods on those objects to format them to a string if you require a different output.

The datetime.strftime() method would be best suited for your purposes:

dtobject.strftime('%d-%b-%Y')

Demo:

>>> import datetime
>>> dtobject = datetime.datetime(2999, 12, 31, 0, 0)
>>> dtobject.strftime('%d-%b-%Y')
'31-Dec-2999'

If, however, Oracle is really returning objects with the year set to 99 (not 2999) you need to repair the data:

if dtobject.year < 100:
    dtobject = dtobject.replace(year=dtobject.year + 2900)



回答2:


You can use strftime.

For example:

>>> import datetime
>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
2013-08-13 13:10

In your case, this can make it:

strftime("%d-%b-%Y")

where:

%b     locale's abbreviated month name (e.g., Jan)
%d     day of month (e.g., 01)
%Y     year


来源:https://stackoverflow.com/questions/18207415/getting-date-fields-from-oracle-in-correct-format-using-python-and-cx-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!