How to Extract or Convert Time Data from a String in SQL

To extract or convert time data from a string in SQL, use the TO_TIMESTAMP function. This function takes two arguments: the string you want to convert and the format of the string. For example, if you wanted to convert the string '2021-02-01' to a timestamp, you would use the following query:

SELECT TO_TIMESTAMP('2021-02-01', 'YYYY-MM-DD');

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called events with the following data:

events
namedate
Party2021-02-01
BBQ2021-03-15
Concert2021-04-30


If you wanted to convert the date column to a timestamp, you would use the following query:

SELECT TO_TIMESTAMP(date, 'YYYY-MM-DD') FROM events;

This query would return the following result:

TO_TIMESTAMP('2021-02-01', 'YYYY-MM-DD')
TO_TIMESTAMP('2021-03-15', 'YYYY-MM-DD')
TO_TIMESTAMP('2021-04-30', 'YYYY-MM-DD')

Additional Info

The TO_TIMESTAMP function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database.

Want to build your own LLM Apps with AirOps👇👇