当字符串只有两位数字表示一年时如何将字符串转换为日期格式(Oracle、Netezza)

How to convert string to date format when string has only two digits for a year (Oracle, Netezza)

我有这个问题数据库:在 Oracle 和 Netezza 上。

问题:我有一个字符串:16101211213。该字符串表示:YYMMDDHH24MMSS。我需要将其转换为日期格式 YYYY-MM-DD HH24:MM:SS。所以在途中我需要添加两位数字(在字符串前面)。我知道日期是二十一世纪的。所以我需要 20 在 begining.So 结果我应该得到 2016-10-12 21:12:13

有人可以帮我吗?我尝试了很多选项(主要是在 Netezza 上)但无法弄清楚。

非常感谢!

RR 可能是你的救星。

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> with test as (select '16101211213' datum from dual)
  2  select to_date(datum, 'rrmmddhh24miss') result
  3  from test;

RESULT
-------------------
12.10.2016 11:21:03

SQL>

哦,还有 - 小心!您使用了错误的格式掩码几分钟;它是"MI",而不是"MM"(这是)。

[编辑:使用不同的格式掩码显示结果]

SQL> with test as (select '16101211213' datum from dual)
  2  select
  3    to_date(datum, 'rrmmddhh24miss') result_1,
  4    to_char(to_date(datum, 'rrmmddhh24miss'), 'mm/dd/yyyy hh:mi:ss am') result_2
  5  from test;

RESULT_1            RESULT_2
------------------- ----------------------
12.10.2016 11:21:03 10/12/2016 11:21:03 AM

SQL>

您可以回复 Oracle 通过使用 YY 或 RR format model elements 来推断年份,或者连接世纪值并使用 YYYY。

如果你真的确定日期都是 21 世纪的,那么使用连接和 YYYY:

to_date('20' || tistamp, 'yyyymmddhh24miss')

将与使用 YY(使用当前日期决定世纪)的行为相同:

to_date(tistamp, 'yymmddhh24miss')

如果所有年份都低于 50,那么 RR (which uses the current date's century or the last century depending on the supplied 2-digit year) 也会得到相同的结果:

to_date(tistamp, 'rrmmddhh24miss')

但是如果任何值是 50 或以上 RR 和 YY/YYYY 表现不同。由于这些似乎是事件时间戳,它们不太可能在未来出现,但有一天差异可能仍然很重要。 (但是,最终,假设 21 世纪也可能无效...)

差异的快速演示,使用您的示例值和其他几个,通过 CTE 提供:

alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';

with your_table(tistamp) as (
  select '16101211213' from dual
  union all select '491231235959' from dual
  union all select '500101000000' from dual
)
select to_date('20' || tistamp, 'yyyymmddhh24miss') as yyyy,
  to_date(tistamp, 'yymmddhh24miss') as yy,
  to_date(tistamp, 'rrmmddhh24miss') as rr
from your_table;

YYYY                YY                  RR                 
------------------- ------------------- -------------------
2016-10-12 11:21:03 2016-10-12 11:21:03 2016-10-12 11:21:03
2049-12-31 23:59:59 2049-12-31 23:59:59 2049-12-31 23:59:59
2050-01-01 00:00:00 2050-01-01 00:00:00 1950-01-01 00:00:00

当然,所有这些也适用于 to_timestamp();因为您没有小数秒或时区信息,所以只要您的客户知道 Oracle 日期有时间成分,使用日期应该没问题。