SQL DatePart Not Working With ISO 8601 Formatted Date & Time
Given a properly formatted ISO 8601 date time of 2024-06-23T06:03:00Z using SQL DatePart results in an error:
[SQLCODE: <-400>:<Fatal error occurred>]
[%msg: <Invalid input to DATEPART() function: datepart='ss', datetime value='2024-06-23T06:03:00Z')>]
If I remove the trailing Z (for Zulu / UTC time) and leave the T, DatePart works fine.
I have also tried various ± offsets from UTC e.g. +0400 and that also results in the same SQL error
I can Trim the trailing "Z", but I would hope that DatePart would work with an acceptably formatted ISO 8601 date time string without having to go through the machinations of trimming the data.
Any help or suggestions on how to use SQL DatePart with ISO 8601 formatted Date Time strings would be appreciated.
This is the query I was experimenting with:
select 'YEAR: '||DATEPART(YEAR,'2024-06-23T06:03:00Z')
UNION
select 'MONTH: '||DATEPART(MONTH,'2024-06-23T06:03:00Z')
UNION
select 'DAY: '||DATEPART(DAY,'2024-06-23T06:03:00Z')
UNION
select 'HOUR: '||DATEPART(HOUR,'2024-06-23T06:03:00Z')
UNION
select 'MINUTE: '||DATEPART(MINUTE,'2024-06-23T06:03:00Z')
UNION
select 'SECOND: '||DATEPART(SECOND,'2024-06-23T06:03:00Z')
ISO 8601 date format is not an accepted format for the SQL DATEPART function.
You can check the supported formats in the DATAPART SQL Documentation.
I'm afraid it does not woks fine:
select 'YEAR: '||DATEPART(YEAR,'2024-06-23T06:03:00')
result:
YEAR: 1900
Try:
select 'YEAR: '||DATEPART(YEAR,$TRANSLATE('2024-06-23T06:03:00Z','TZ',' '))
Hi!
You need first convert the formatted date and time string to a standard timestamp. Unfortunately, the built-in TO_TIMESTAMP function is not suitable for your case.
Next, you need determine whether the time zone will be taken into account or not.
For tests, you can use https://www.timestamp-converter.com / (ISO 8601 section).
Here is a small example:
Result (for me):
Using via SQL: