I'm having trouble inserting a field into the database, type conversion keeps timezone
UPDATE order o
SET o.data_envio = CONVERT( '2022-01-05T14:47:00-03:00', DATETIME );
1292 - Truncated incorrect datetime value: '2022-01-05T14:47:00-03:00'
You want to convert the timestamp with the STR_TO_DATE() function:
https://mariadb.com/kb/en/str_to_date/
Like this:
UPDATE order o
SET o.data_envio = STR_TO_DATE( '2022-01-05T14:47:00-03:00', '%Y-%m-%dT%H:%i:%s')
Only drawback here is that you will lose the timezone information.
This requires mysql 8; it will not work on 5.7 or earlier, or any version of mariadb (through at least 10.7.1).
Instead, you can do:
SET o.data_envio = convert_tz('2022-01-05T14:47:00','-03:00','+00:00')
Note that the first parameter cannot have the offset; it has to just be provided as the second parameter. If you have to remove it in your sql, not your code, and your dates are always well formed (no missing - or :, always two digits for each part except four for year), you can do:
UPDATE `order` o SET o.data_envio = CONVERT_TZ(
SUBSTRING('2022-01-05T14:47:00-03:00' FROM 1 FOR 19),
SUBSTRING('2022-01-05T14:47:00-03:00' FROM 20),
'+00:00'
)
Related
I'm using MySQL version: 5.7.22
So I'm trying to have a table that contains a date column from string. The text field contains data in following DateTime format "d/m/YYYY h:m:s" format. e.g. "14/11/2018 20:10:04 +00:00".
I want to alter the table with a new column that is of the following format '%Y-%m-%d'. I get a
Data truncation: Truncated incorrect date value error
when I try to update the table. But I get the result when I just use a select statement to convert from string to date.
UPDATE BIG_DATA SET BIG_DATA.RealDate = ( SELECT x.d
From (SELECT (DATE_FORMAT(STR_TO_DATE(BIG_DATA.Date , '%d/%m/%Y'), '%Y-%m-%d')) as d
FROM BIG_DATA) as x);
Any help would be grateful!
The reason you are getting an error is that the warning for an incorrect date value (one that produces a value with zeros in it) that is produced by STR_TO_DATE on a SELECT is promoted to an error when you attempt to do an UPDATE. For example, if you do
SELECT STR_TO_DATE('14/11/2018 20:10:04 +00:00', '%d/%m/%Y');
SHOW WARNINGS
Your output will be:
2018-11-14
Warning 1292 Truncated incorrect date value: '14/11/2018 20:10:04 +00:00'
You can work around this by only supplying the date part (the leftmost 10 characters) of the string to STR_TO_DATE:
SELECT STR_TO_DATE(LEFT('14/11/2018 20:10:04 +00:00', 10), '%d/%m/%Y');
SHOW WARNINGS
Output is simply 2018-11-14
This then allows you to create your other column and UPDATE it from the date column:
ALTER TABLE big_data ADD
realdate DATE;
UPDATE big_data
SET realdate = STR_TO_DATE(LEFT(date, 10), '%d/%m/%Y');
SELECT * FROM big_data
Another possibility you might want to consider is using a generated column:
ALTER TABLE big_data ADD
realdate DATE AS (STR_TO_DATE(date, '%d/%m/%Y'));
SELECT * FROM big_data
In both cases the output is
date realdate
14/11/2018 20:10:04 +00:00 2018-11-14
Demo on dbfiddle
With the string DATETIME yyyymmddhhmmss like 20160125173013, I would like to convert this string into hh:mm:ss (17:30:13) as a new column called "Time" in a table with sql update statement. However I am only able to convert it into 17:30 using the stuff function.
Is there any possible solution to convert?
In my statement
UPDATE db
SET Time =convert(time, stuff(substring(DATETIME,9,6),3,2,':'))
FROM db
WHERE Time IS NULL
Real Output=17:13:00.0000000
But my expected output is 17:13:00
Thanks a lot!
Here is the miracle for mysql:
SELECT time(str_to_date('20160125173013', '%Y%m%d%H%i%s'));
Do you have an actual DATETIME field? If so you can use DATE_FORMAT():
UPDATE mytable SET my_time=DATE_FORMAT(my_date, '%H:%i:%s')
If you don't have a native DATETIME field I hope you can convert it to one, as irregular, quirky formats cause trouble and introduce a lot of overhead when parsing to convert. STR_TO_DATE() can do the opposite of DATE_FORMAT() and convert from arbitrary strings to native DATE or DATETIME values.
Don't confuse STORAGE with PRESENTATION
Declare #YourTable table (DateTime varchar(25),Time time)
Insert Into #YourTable values
('20160125173013',null)
Update #YourTable
Set Time = stuff(left(right(DateTime,6),4),3,0,':')
Select *
,FormatedTime = Format(cast(Time as datetime),'HH:mm')
From #YourTable
Returns
DateTime Time FormatedTime
20160125173013 17:30:00.0000000 17:30
Based on the use of the STUFF function I believe this is Microsoft SQL Server, and not MySql.
Therefor, you can do something like this:
UPDATE db
SET [Time] = CAST(SUBSTRING([DATETIME], 9, 2) +':'+
SUBSTRING([DATETIME], 11, 2) +':'+
RIGHT([DATETIME], 2) As Time)
WHERE [Time] IS NULL
Your string is no format, SQL Server will cast implicitly
DECLARE #YourDateTimeString VARCHAR(100)='20160125173013';
The following query will cut the first 8 digits and cast them to DATE, which works implicitly (unseparated format). The time is cut from the right side, then the two :-signs are stuffed into the right places:
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME);
The result
2016-01-25 17:30:13.0000000
If you need this as string without the trailing .0000000 (which is a pure output format question and should be done in your presentation layer!) you can just use LEFT(). The input of this function is string (again implicitly casted), the output is a text which looks like a time.
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,LEFT(CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME),8);
The result
2016-01-25 17:30:13
If you ar eusing SQL server then use Convert function
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
--Declare
set #VarCharDate = '20160125173013' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' +
SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2)
+ ' ' + SUBSTRING(#VarCharDate,9,2)
+':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
select Convert(varchar(8),convert(datetime, #VarCharDate1, 120),114)
If I use a QSqlTableModel to access a MySQL database I can convert a TIMESTAMP field using the following:
QDateTime dateTime = index(section, column).data().toDateTime();
QString str = dateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
So str shows, i.e. 2014-06-22 22:11:44.221.
But I want to access the database using QSqlQuerry, so I do:
QDateTime dateTime = query.value(column).toDateTime();
str = dateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
But now I'm missing the milliseconds, str shows 2014-06-22 22:11:44.000. What's the proper way to see the milliseconds?
If I do str = query.value(column).toString(); then I get 2014-06-22T22:11:44.
From this page:
https://dev.mysql.com/doc/refman/5.6/en/datetime.html
A DATETIME or TIMESTAMP value can include a trailing fractional
seconds part in up to microseconds (6 digits) precision. In
particular, as of MySQL 5.6.4, any fractional part in a value inserted
into a DATETIME or TIMESTAMP column is stored rather than discarded.
So, the millisecond is there in MySQL! But the query.value() does not get it - at this point in the Qt history as pointed by #peppe here.
Relating back to the original question: There is no proper way to see the millisecond since the query does not have it. One alternative could be to modify the query, from:
SELECT timestamp FROM table;
to
SELECT DATE_FORMAT(timestamp, '%Y-%c-%e %H:%i:%s.%f') as timestamp FROM table;
And then finish the job with:
QString str = query.value(column).toString();
QDateTime dateTime = QDateTime::fromString(str, "yyyy-MM-dd hh:mm:ss.zzz000");
I got the insight from here.
From MySQL 5.1 documentation:
A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision. Although this fractional part is recognized, it is discarded from values stored into DATETIME or TIMESTAMP columns.
It seems like seconds is the best you can do with timestamp.
I am trying to convert a database with all values stored as VARCHAR into the correct column type eg: INT, DATE, DECIMAL etc...
Problem is, that the columns date_order, date_billed and date_paid are stored in different formats
I still get a 1292 Truncated incorrect date value: '05/18/2011' errors and have pretty much no clue what to do since that exact date format is listed as CASE
My code:
SELECT
CAST(`ar_no` AS UNSIGNED),
CAST(`accession_id` AS UNSIGNED),
CAST(`client_id` AS UNSIGNED),
CAST(`insurance_id` AS UNSIGNED),
CAST(`test_id` AS UNSIGNED),
CASE
WHEN `date_paid` = '0' THEN `date_paid` = '00/00/0000'
WHEN LENGTH(DATE(STR_TO_DATE(`date_order`, '%m/%d/%y'))) IS NOT NULL THEN STR_TO_DATE(`date_order`, '%m/%d/%y')
WHEN LENGTH(DATE(STR_TO_DATE(`date_order`, '%m/%d/%Y'))) IS NOT NULL THEN STR_TO_DATE(`date_order`, '%m/%d/%Y')
END,
CASE
WHEN `date_paid` = '0' THEN `date_paid` = '00/00/0000'
WHEN LENGTH(DATE(STR_TO_DATE(`date_billed`, '%m/%d/%y'))) IS NOT NULL THEN STR_TO_DATE(`date_billed`, '%m/%d/%y')
WHEN LENGTH(DATE(STR_TO_DATE(`date_billed`, '%m/%d/%Y'))) IS NOT NULL THEN STR_TO_DATE(`date_billed`, '%m/%d/%Y')
END,
CASE
WHEN `date_paid` = '0' THEN `date_paid` = '00/00/0000'
WHEN LENGTH(DATE(STR_TO_DATE(`date_paid`, '%m/%d/%y'))) IS NOT NULL THEN STR_TO_DATE(`date_paid`, '%m/%d/%y')
WHEN LENGTH(DATE(STR_TO_DATE(`date_paid`, '%m/%d/%Y'))) IS NOT NULL THEN STR_TO_DATE(`date_paid`, '%m/%d/%Y')
END,
CAST(`amount_billed` AS DECIMAL(15,2)),
CAST(`amount_received` AS DECIMAL(15,2)),
CAST(`amount_adjusted` AS DECIMAL(15,2))
FROM `acs`.`billing_unformatted`;
Mysql only excepts dates in YYYY-MM-DD format. That is why you are getting errors such as 1292 Truncated incorrect date value: '05/18/2011'
You can change this in Excel before doing your import.
In order to change the date format in excel: right click on the top cell. Choose format cells from the drop down list. change the local to something like 'Afrikans'. Choose the format that looks like 2001-03-14. Use the top cell to fill down. Then save the document.
Just a quick note: Excel sometimes tries to do too much and will revert this column back to a the English(U.S) default time zone. So, if you plan on doing more editing make sure that the column has not reverted back.
Here is a link to more string literals on dev.mysql.
This stored procedure and post might help you as well: Error code 1292
I converted a database from MS SQL to MySql using workbench. There is a table that has a column called ActivityDate (datetime(6)) . For some reason, when that column got converted it has a dot in the date like (2013-05-03 11:20:20.420000) .
I want to remove the .420000 or whatever number is after the dot. I tried doing SUBSTRING_INDEX(ActivityDate,'.',1) but that didn't work, the last digits would just be .000000
I also tried UPDATEalerts.activitylogSETActivityDate= date_format(ActivityDate, '%Y-%m-%d %H:%i') WHEREactivitylog.ActivityLogID= 5;
And same issue... I get .000000 at the end
How can I do this?
Simply change the data type of the column to exclude the fractional part.
ALTER TABLE alerts.activitylog MODIFY ActivityDate DATETIME;
The type datetime(6) means 6 digits after the decimal point.
See the MySQL date and time fractional support documentation for details.
If you just want to select the datetime without the ms (like I was when I found this question) then the below CAST does the job:
SELECT CAST(created_at AS DATETIME) AS created_at_without_ms