Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert VARCHAR timestamp to TIMESTAMP?

I have a time stamp of the form "17:16:28 Sep 13, 2011 PDT" in a MySQL database. The type of the field in the database is VARCHAR. I would like to convert this VARCHAR to a field of type TIMESTAMP in MySQL.

I tried a few solutions suggested elsewhere on this site, such as using a string_to_time function, but these solutions all start from a different type of timestamp.

How do I convert the VARCHAR timestamp mentioned above to a TIMESTAMP recognised by MySQL, in such a way that I can sort my data by date?

like image 297
Mark Avatar asked Oct 17 '12 11:10

Mark


People also ask

How do I convert a string to TIMESTAMP?

To convert a date string to a timestamp: Pass the date string to the Date() constructor. Call the getTime() method on the Date object. The getTime method returns the number of milliseconds since the Unix Epoch.

How do I convert a TIMESTAMP in python?

We can convert a datetime object into a timestamp using the timestamp() method. If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the tzinfo parameter of the datetime object and then call the timestamp() method.

How do I cast a TIMESTAMP?

You can, however, cast a TIMESTAMP to a DATE and then cast the DATE to a CHAR of less than 24 characters. For example: SELECT CAST (CAST (timestamp_col AS DATE) AS CHAR(10)) FROM table1; CHAR data type into a DATE TIME or TIMESTAMP data type.


2 Answers

You can do this by using STR_TO_DATE function in MySQL, try this:

SELECT STR_TO_DATE("17:16:28 Sep 13, 2011 PDT", '%H:%i:%s %b %d, %Y PDT');

EDIT:

SELECT STR_TO_DATE(field_name, '%H:%i:%s %b %d, %Y PDT') AS new_time
FROM table_name;
like image 131
Omesh Avatar answered Sep 24 '22 02:09

Omesh


Use str_to_date with formatting:

select unix_timestamp(str_to_date("17:16:28 Sep 13, 2011 PDT","%T %b %d, %Y PDT"));

If the day part (e.g.: 13) is not represented as 01, 02..etc. but 1, 2, 3 when it's only one digit, change the %d to %e

Be careful because the timezone will not be recognized, it's only a string literal for the formatting! If you have different timezones for different records you should use the convert_tz() function to get the proper timestamp.

like image 23
Andrew Avatar answered Sep 26 '22 02:09

Andrew