使用Python和cx-oracle从oracle以正确的格式获取日期字段 [英] getting date fields from oracle in correct format using Python and cx-oracle
问题描述
我正在从一个Oracle数据库中检索数据负载,然后将其插入结构上相同的另一个非链接数据库中。
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.
我正在这样做:
select * from xxx where id = parameter
和
Select COLUMN_NAME from user_tab_columns where table_name=xxx
然后使用zip将其作为表名添加到字典中:用于从中构建插入内容的数据
then with zip putting them in a dictionary as table_name:Data to build the insert from
问题是它返回日期字段为datetime.datetime(99,12,31,0,0)。我需要将此作为2999年12月31日。如何获得它以这种方式返回它,或者我需要创建一个正则表达式来做到这一点?
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
推荐答案
cx_Oracle
数据库适配器为您提供 datetime.datetime()
对象 。如果需要其他输出,请在这些对象上使用方法将其格式化为字符串。
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.
datetime.strftime()
方法最适合您的目的:
The datetime.strftime()
method would be best suited for your purposes:
dtobject.strftime('%d-%b-%Y')
演示:
>>> import datetime
>>> dtobject = datetime.datetime(2999, 12, 31, 0, 0)
>>> dtobject.strftime('%d-%b-%Y')
'31-Dec-2999'
但是,如果Oracle确实返回的年份设置为 99
(不是 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)
这篇关于使用Python和cx-oracle从oracle以正确的格式获取日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!