Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presto SQL - Converting a date string to date format

Tags:

sql

presto

I'm on presto and have a date formatted as varchar that looks like -

7/14/2015 8:22:39 AM 

I've looked the presto docs and tried various things(cast, date_format, using split_part to parse and then cast) and am not getting this to convert to a date format that I can use with functions like date_diff.

I've tried:

cast(fieldname as timestamp) date_format(fieldname, '%Y-%m-%d %T) 

Both give me an error like this

'Value cannot be cast to timestamp: 3/31/2016 6:05:04 PM' 

How do I convert this?

like image 369
Moosa Avatar asked Oct 05 '16 17:10

Moosa


People also ask

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


2 Answers

I figured it out. The below works in converting it to a 24 hr date format.

select date_parse('7/22/2016 6:05:04 PM','%m/%d/%Y %h:%i:%s %p') 

See date_parse documentation in Presto.

like image 121
Moosa Avatar answered Oct 03 '22 14:10

Moosa


You can also do something like this

date(cast('2016-03-22 15:19:34.0' as timestamp))

like image 24
Russell Lego Avatar answered Oct 03 '22 13:10

Russell Lego