简体   繁体   English

Oracle SQL:从时间戳时区提取日期和时间

[英]Oracle SQL: Extract Date & Time from Timestamp Timezone

I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT . 我的表格中有一个START_DATE列,其值的格式YYYY-MM-DD HH:MM:SS AM/PM GMT I'm trying to insert those values into another table but i'm getting a date format not recognized error. 我正在尝试将这些值插入到另一个表中,但出现了date format not recognizeddate format not recognized错误。 How do I fix this? 我该如何解决?

Sample SQL statement 示例SQL语句

INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT
    TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'),
    TO_DATE(TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'), 'YYYY-MM-DD HH:MI:SS AM')
FROM TABLE_DATE

Sample Data 样本数据

2016-01-21 09:31:49 AM GMT
2016-02-22 06:37:32 PM GMT
2016-02-23 07:10:52 PM GMT
2016-03-15 08:54:40 PM GMT
2016-03-16 12:10:52 AM GMT

If it helps, these are the datatypes of the two columns in TABLE2 如果有帮助,这些是表2中两列的数据类型

DATE_WITH_TIMEZONE TIMESTAMP WITH TIME ZONE DATE_WITH_TIMEZONE TIMESTAMP TIME ZONE

DATE_WITHOUT_TIMEZONE DATE DATE_WITHOUT_TIMEZONE DATE

I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT 我的表格中有一个START_DATE列,其值的格式YYYY-MM-DD HH:MM:SS AM/PM GMT

Assuming that your START_DATE column is of the DATE data type then your statement is incorrect; 假设您的START_DATE DATE数据类型,则您的陈述不正确; a DATE column has no format and it is stored internally as 7-bytes . DATE列没有格式,并且内部存储为7个字节 It is only when it is passed to the user interface you are using to access the database that that UI will format the date (and not the database). 只有在将其传递到用于访问数据库的用户界面时,UI才会格式化日期(而不是数据库)。 SQL/Plus and SQL developer will format the date using the NLS_DATE_FORMAT session parameter (which is set per user session and can be changed) so relying on this format can lead to "interesting" bugs where the code you are using does not change but will start and stop working for different users depending on their session settings. SQL / Plus和SQL Developer将使用NLS_DATE_FORMAT会话参数(在每个用户会话中设置并可以更改)格式化日期,因此,依靠这种格式可能会导致“有趣的”错误,在这些错误中您使用的代码不会更改,但会根据他们的会话设置为不同的用户启动和停止工作。

You can just do: 您可以这样做:

INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT FROM_TZ( CAST( START_DATE AS TIMESTAMP ), 'GMT' ),
       START_DATE
FROM   TABLE_DATE;

If your START_DATE column is of a string datatype (why would you do this?) then you will need to convert it to the appropriate type: 如果您的START_DATE列是字符串数据类型(为什么要这样做?),则需要将其转换为适当的类型:

INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ),
       CAST( TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ) AS DATE )
FROM   TABLE_DATE;

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

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