String to Date-time in SQL [duplicate] - mysql

I've a column in a table (varchar) with dates in this format
2013-09-05T10:10:02Z
How do I convert this into datetime format and save it in another column, using an update query?

You can use the STR_TO_DATE function:
UPDATE table1 SET col2 = STR_TO_DATE(col1,'%Y-%m-%dT%TZ')
Example:
mysql> select STR_TO_DATE('2013-09-05T10:10:02Z','%Y-%m-%dT%TZ');
+----------------------------------------------------+
| STR_TO_DATE('2013-09-05T10:10:02Z','%Y-%m-%dT%TZ') |
+----------------------------------------------------+
| 2013-09-05 10:10:02 |
+----------------------------------------------------+
1 row in set (0.00 sec)

You can also use CAST('2013-09-05T10:10:02Z' AS DATETIME) which does not require a format definition as in STR_TO_DATE().

If you want to take care of the timezone just use this query, and use the mysql timezone
mysql> select CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", ##session.time_zone);
+-------------------------------------------------------------------+
| CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", ##session.time_zone) |
+-------------------------------------------------------------------+
| 2013-09-05 12:10:02 |
+-------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
or any other timezone
mysql> select CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", "+03:00");
+--------------------------------------------------------+
| CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", "+03:00") |
+--------------------------------------------------------+
| 2013-09-05 13:10:02 |
+--------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

I tried using the cast method from above but would get the truncated error as describe in the comments.
You can also use CAST('2013-09-05T10:10:02Z' AS DATETIME) which does not require a format definition as in STR_TO_DATE().
I would consistently get: Error: Truncated incorrect datetime value: '2011-10-02T23:25:42Z'
I fixed it by casting the value to an # variable before using it in my query. Here is an example in a Stored Procedure:
CREATE PROCEDURE `new_procedure`(IN p_date VARCHAR(50), p_text VARCHAR(500))
BEGIN
SET #datestring = CAST(p_date AS DATETIME);
-- used for debugging
SELECT #datestring, p_text;
INSERT INTO testtable(timestamp, text) VALUES(#datestring, p_text);
END

Related

Passing a computed column value to FROM_UNIXTIME in MySQL

I have a table with a column 'ts_min' having time since epoch in minutes
ts_min
--------
24429000
24428340
24427680
I tried the following query to get date representation of these values
select ts_min, from_unixtime(ts_min*60000) from mytable;
from_unixtime is returning null.
ts_min from_unixtime (ts_min * 60000)
----------------------------------------
24429000 NULL
24428340 NULL
24427680 NULL
What is the correct syntax to pass computed value from a column to from_unixtime
yes, 60 is ok. see sample:
sample
MariaDB [(none)]> select from_unixtime(24429000*60);
+----------------------------+
| from_unixtime(24429000*60) |
+----------------------------+
| 2016-06-12 16:00:00 |
+----------------------------+
1 row in set (0.00 sec)
MariaDB [(none)]>
You can use both sec_to_time and from_unixtime
select SEC_TO_TIME(ts_min*60) from dual
or
select from_unixtime(ts_min*60) from dual

Why does the CAST() function return the wrong date?

I am trying to get the date part from a timestamp field.
I used this SQL query:
select timestamp, CAST(timestamp as date) as date from messages
I got the following result:
--------------------------------------------
| timestamp | date |
--------------------------------------------
| 2016-05-15 10:22:54 | 2016-05-16 |
--------------------------------------------
As shown above, the date field produced returns the wrong date 2016-05-16 whereas the original date is 2016-05-15.
How can we resolve this issue?
Thats not a issue !!! Its only set the wrong time_zone. see sample
get current time_zone
SHOW GLOBAL VARIABLES LIKE 'time_zone'; -- systemwide setting
SHOW VARIABLES LIKE 'time_zone'; -- session setting
sample
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-15 20:22:54 | 2016-05-15 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]> SET time_zone ='-12:00';
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-14 20:22:54 | 2016-05-14 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]>
Use date not cast because is not casting but a format
select timestamp, date(timestamp) as my_date from messages
I would suggest you to use the DATE_FORMAT function and not the CAST since you are formatting the date like
SELECT `timestamp`, DATE_FORMAT(`timestamp`, '%Y-%m-%d) as my_date from messages
Also note that both CAST and DATE function internally call Item_date_typecast function so there is no such difference between them.
Try this
select timestamp, cast(timestamp as date format 'yyyymmddhhmmss') as date from messages

Mysql - How to convert date from ISO 8601 format and save to mysql column?

I've a column in a table (varchar) with dates in this format
2013-09-05T10:10:02Z
How do I convert this into datetime format and save it in another column, using an update query?
You can use the STR_TO_DATE function:
UPDATE table1 SET col2 = STR_TO_DATE(col1,'%Y-%m-%dT%TZ')
Example:
mysql> select STR_TO_DATE('2013-09-05T10:10:02Z','%Y-%m-%dT%TZ');
+----------------------------------------------------+
| STR_TO_DATE('2013-09-05T10:10:02Z','%Y-%m-%dT%TZ') |
+----------------------------------------------------+
| 2013-09-05 10:10:02 |
+----------------------------------------------------+
1 row in set (0.00 sec)
You can also use CAST('2013-09-05T10:10:02Z' AS DATETIME) which does not require a format definition as in STR_TO_DATE().
If you want to take care of the timezone just use this query, and use the mysql timezone
mysql> select CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", ##session.time_zone);
+-------------------------------------------------------------------+
| CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", ##session.time_zone) |
+-------------------------------------------------------------------+
| 2013-09-05 12:10:02 |
+-------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
or any other timezone
mysql> select CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", "+03:00");
+--------------------------------------------------------+
| CONVERT_TZ("2013-09-05T10:10:02Z", "+00:00", "+03:00") |
+--------------------------------------------------------+
| 2013-09-05 13:10:02 |
+--------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
I tried using the cast method from above but would get the truncated error as describe in the comments.
You can also use CAST('2013-09-05T10:10:02Z' AS DATETIME) which does not require a format definition as in STR_TO_DATE().
I would consistently get: Error: Truncated incorrect datetime value: '2011-10-02T23:25:42Z'
I fixed it by casting the value to an # variable before using it in my query. Here is an example in a Stored Procedure:
CREATE PROCEDURE `new_procedure`(IN p_date VARCHAR(50), p_text VARCHAR(500))
BEGIN
SET #datestring = CAST(p_date AS DATETIME);
-- used for debugging
SELECT #datestring, p_text;
INSERT INTO testtable(timestamp, text) VALUES(#datestring, p_text);
END

MySQL: Get local time for a specific time zone

Here's a simple version of the table users:
+--------------+-------------------+
| id | timezone |
+--------------+-------------------+
| 1 | 'Europe/Helsinki' |
| 2 | 'Europe/Paris' |
+--------------+-------------------+
I want to know what's the local time for each one of these users (depending on their time zones), so that I can select users for who it's 4pm for example.
I'm using the LAMP stack, but I'd like to do that using MySQL only (not selecting all users and running them in a PHP loop).
Use the CONVERT_TZ for this:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz
SELECT * FROM users WHERE hour(CONVERT_TZ(now(), server_tz, `timezone`))=16
You can change the timezone with set time_zone:
mysql> set time_zone='Europe/Helsinki';
mysql> select now();
2012-09-21 16:15:06
mysql> set time_zone='Europe/Paris';
mysql> select now();
2012-09-21 15:15:40
Using this you can, for example, define a function that returns the current time for the user's timezone:
create function current_time_in_tz(tz varchar(40)) returns datetime
begin
set #old_tz = ##session.time_zone;
set time_zone=tz;
set #now = now();
set time_zone=#old_tz;
return #now;
end
select id, current_time_in_tz(timezone) from users;
Note that DATE, TIME and DATETIME values don't depend on the time zone, so values from columns of these types are not automatically adjusted when querying. TIMESTAMP values are adjusted:
mysql> create temporary table tbl (dt datetime, ts timestamp);
mysql> insert into tbl values (now(),now());
mysql> select * from tbl;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2012-09-21 15:21:56 | 2012-09-21 15:21:56 |
+---------------------+---------------------+
mysql> set time_zone='Europe/Helsinki';
mysql> select * from tbl;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2012-09-21 15:21:56 | 2012-09-21 16:21:56 |
+---------------------+---------------------+
If set time_zone fails with this error:
ERROR 1298 (HY000): Unknown or incorrect time zone: 'Europe/Helsinki'
you need to load the time zone info into mysql with a command like this:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
For more info see http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
A more generic (not depending on the timezone of the server) solution than Nin's answer would be:
SELECT * FROM users WHERE hour( CONVERT_TZ(UTC_TIMESTAMP(), 'UTC', timezone) )=16
It would be nice if MySQL had a function like NOW_TZ(timezone).

Set Default values in mysql id and timestamp column?

I want to set my id in mysql table to default value say '000001' or'TodaysDate followed by 000001'..and same should be also auto_incremented.
how can we do this?
and also how set default value in TIMESTAMP column not by using 'CURRENT_TIMESTAMP'
such as '2012-04-01' and when update trigger will get fire it should get updated with todays date.
How to do this?
I want to set my id in mysql table to default value say '000001'.
If I were you I will leave it like id int, auto increment and when make the select I'll use the lpad function:
mysql> select lpad('1',6,'0');
+-----------------+
| lpad('1',6,'0') |
+-----------------+
| 000001 |
+-----------------+
1 row in set (0.00 sec)
about the timestamp I'll let that someone else answer, because what I'm thinking is do the same, use the current_timestamp and with mysql function convert to it how you want to:
mysql> select left(now(),10);
+----------------+
| left(now(),10) |
+----------------+
| 2012-06-01 |
+----------------+
1 row in set (0.00 sec)'
EDIT:
mysql> select concat(replace(left(now(),10),'-',''),lpad('1',6,'0'));
+--------------------------------------------------------+
| concat(replace(left(now(),10),'-',''),lpad('1',6,'0')) |
+--------------------------------------------------------+
| 20120601000001 |
+--------------------------------------------------------+
1 row in set (0.00 sec)
It looks like you answered your own question: specifically you want a 'before insert/update' trigger that sets the value for you.
CREATE TRIGGER my_autoinc BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test1 SET NEW.id_column = concat(today(), <some value>);
END;