Convert string with time zone offset to datetime in Athena

There is a column of type varchar in MySQL table that contains datetime data like
‘2021-08-17 06:55:22.819-0400’ which has the time zone offset information included.

How can it be converted to datetime(3) in a select statement in Athena?
Basically ‘2021-08-17 06:55:22.819-0400’ >>> 2021-08-17 10:55:22.819

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use the parse_datetime function, like this:

SELECT parse_datetime('2021-08-17 06:55:22.819-0400', 'yyyy-MM-dd HH:mm:ss.SSSZ')

If you want the time converted to UTC you can append AT TIME ZONE 'Z', like this:

SELECT parse_datetime('2021-08-17 06:55:22.819-0400', 'yyyy-MM-dd HH:mm:ss.SSSZ') AT TIME ZONE 'Z'

Method 2

If all dates are exactly in this format you can replace space with T and use from_iso8601_timestamp, which will return timestamp with time zone and then you can handle timezone either using AT TIME ZONE 'UTC' or just custing to timezone:

select cast(from_iso8601_timestamp(replace('2021-08-17 06:55:22.819-0400', ' ', 'T')) AS timestamp) 

Output:

_col0
2021-08-17 10:55:22.819


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x