简体   繁体   English

如何将sql中的数字转换为日期

[英]How to convert number to date in sql

I am fetching data from oracle using sql in python. There are columns having integer values.我正在使用 python 中的 sql 从 oracle 获取数据。有些列具有 integer 值。 I want to convert those column values to dates while retrieving data.我想在检索数据时将这些列值转换为日期。

connection = cx_Oracle.connect(user, pwd, dsn, encoding="UTF-8")
cursor = connection.cursor()
results = cursor.execute("SELECT TO_DATE(DATECREATED,'yyyymmdd') as DATECREATED from ARADMIN.EPM_TechnicianInformation").fetchall()

It's not working.它不工作。

the above query is giving me errors - DatabaseError:上面的查询给我错误 - DatabaseError:

 ORA-01843: not a valid month

From Oracle 12, you can add a clause to handle errors during conversion due to invalid data:从Oracle 12开始,可以添加一个子句来处理由于无效数据导致的转换过程中的错误:

SELECT TO_DATE(
         DATECREATED
         DEFAULT NULL ON CONVERSION ERROR,
         'yyyymmdd'
       ) as DATECREATED
FROM   ARADMIN.EPM_TechnicianInformation

Which for the sample data:其中样本数据:

CREATE TABLE ARADMIN.EPM_TechnicianInformation ( datecreated ) AS
SELECT 20210929 FROM DUAL UNION ALL  -- A valid date
SELECT 20211301 FROM DUAL;           -- An invalid date as month = 13

Outputs:输出:

DATECREATED创建日期
2021-09-29 00:00:00 2021-09-29 00:00:00
<null> <空>

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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