How to Convert a String to a Timestamp in SQL

Have you ever wanted to convert a string to a timestamp in SQL? It's a common task, and luckily, it's easy to do! In this post, we'll show you how to convert a string to a timestamp in SQL, and provide some helpful examples to get you started.

The Solution

The solution is to use the STR_TO_DATE() 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 2020-10-01 to a timestamp, you would use the following query:

SELECT STR_TO_DATE('2020-10-01', '%Y-%m-%d')

This query would return the result 2020-10-01 00:00:00, which is the timestamp equivalent of the string.

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
event_nameevent_date
Party2020-10-01
Concert2020-11-15

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

SELECT event_name, STR_TO_DATE(event_date, '%Y-%m-%d') FROM events;

This query would return the following results:

events
event_nameevent_date
Party2020-10-01 00:00:00
Concert2020-11-15 00:00:00

Additional Info

The STR_TO_DATE() 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👇👇