ORACLE 12c 中 VARCHAR2 到 TIMESTAMP 的转换

VARCHAR2 to TIMESTAMP conversion in ORACLE 12c

我在 table A 中有一列作为

select create_time from table_a;

值为

08-MAR-19 08.23.47.897000000 PM GMT.

出于某些商业目的,此列已标记为 VARCHAR2。现在我试图获取此列并将值转换为 TIMESTAMP 出于某种目的,如下所示:

SELECT TO_TIMESTAMP(create_time, 'DD-MON-YYYY HH.MI.SS.FF AM') from table_a;

但我收到错误消息:

ORA-01830: date format picture ends before converting entire input string

谁能帮我把这个 varchar 数据转换成时间戳。我尝试这样做的原因是,我需要将这个时间从一个时区转换为另一个时区: 例如:

SELECT FROM_TZ(TO_TIMESTAMP(create_time, 'DD-MON-YYYY HH.MI.SS.FF AM'), 'UTC') AT TIME ZONE 'CET' from table_a;

删除 GMT 使用 REPLACE

WITH A AS (SELECT REPLACE('08-MAR-19 08.23.47.897000000 PM GMT','GMT','') AS D FROM DUAL)
SELECT TO_TIMESTAMP (D, 'DD-MON-YYYY HH.MI.SS.FF AM')
  FROM A
 
SQL> select replace('08-MAR-19 08.23.47.897000000 PM GMT','GMT','') AS RESULT from dual 
  ;

RESULT
--------------------------------
08-MAR-19 08.23.47.897000000 PM

SQL> select to_timestamp(replace('08-MAR-19 08.23.47.897000000 PM GMT','GMT','')) as RESULT from dual ;

RESULT
---------------------------------------------------------------------------
08-MAR-19 08.23.47.897000000 PM

SQL> select from_tz(to_timestamp(replace('08-MAR-19 08.23.47.897000000 PM GMT','GMT','')),'UTC') AT TIME ZONE 'CET' AS RESULT from dual ;

RESULT
---------------------------------------------------------------------------
08-MAR-19 09.23.47.897000000 PM CET

SQL>

末尾的四个字符 GMT 未包含在您的格式字符串中

SELECT TO_TIMESTAMP('08-MAR-19 08.23.47.897000000 PM GMT', 'DD-MON-YYYY HH.MI.SS.FF AM') from dual;

以下内容负责:

SELECT TO_TIMESTAMP(substr(create_time, 1, LENGTH(create_time) -4), 'DD-MON-YYYY HH.MI.SS.FF AM') t from dual;

试试这个。

select  TO_TIMESTAMP( REPLACE(ts, 'GMT', '')) from test_timestamp;

做类似的事情:

to_timestamp(replace(create_time ,'GMT', null))

取决于您的 NLS 设置,包括时间戳格式 - 特别是它具有 RR 年掩码 - 以及月份缩写的语言。这样做会更安全:

to_timestamp(replace(create_time, ' GMT', null),
  'DD-MON-RR HH.MI.SS.FF AM', 'NLS_DATE_LANGUAGE=ENGLISH')

如果时区不总是 GMT,但始终是有效且可识别的区域(例如,不是 BST),那么您可能希望保留完整的 date/time 包括该时区:

to_timestamp_tz(create_time, 'DD-MON-RR HH.MI.SS.FF AM TZR',
  'NLS_DATE_LANGUAGE=ENGLISH')

如果你想把它作为一个简单的时间戳,你可以投射它,可能首先改变到一个特定的区域:

cast(to_timestamp_tz(create_time, 'DD-MON-RR HH.MI.SS.FF AM TZR',
  'NLS_DATE_LANGUAGE=ENGLISH') as timestamp)

cast(to_timestamp_tz(create_time, 'DD-MON-RR HH.MI.SS.FF AM TZR',
  'NLS_DATE_LANGUAGE=ENGLISH') at time zone 'Asia/Tokyo' as timestamp)

或标准化为 UTC(当然,这不会影响 GMT 值,因为它们本质上是相同的):

sys_extract_utc(to_timestamp_tz(create_time, 'DD-MON-RR HH.MI.SS.FF AM TZR',
  'NLS_DATE_LANGUAGE=ENGLISH'))

db<>fiddle