load data infile Date time in mysql results in zeros - mysql

can someone help me with this, my resulting table is showing only zeros for the timestamp. I tried changing the field type to datatime and timestamp but not luck
MYSQL
LOAD DATA LOCAL INFILE 'vals.csv'
INTO TABLE vals
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
IGNORE 1 LINES
(#varTimeSt,NOMINAL,NAME,ID,VAL) SET DATETIME = STR_TO_DATE(#varTimeSt,'%d/%m/%Y %h:%i:%s');
CSV File
DATETIME,NAME,ID,VAL
"25/08/2016 02:00:00",tom,cNum6,12
"25/08/2016 02:00:00",Charles,cNum7,10.58
"25/08/2016 02:00:00",Donal,cNum8,10.18
"25/08/2016 02:00:00",Duncan,cNum7,10.31
Resulting table
DATETIME,NAME,ID,VAL
0000-00-00 00:00:00,tom,cNum6,12
0000-00-00 00:00:00,Charles,cNum7,10.58
0000-00-00 00:00:00,Donal,cNum8,10.18
0000-00-00 00:00:00,Duncan,cNum7,10.31

Your problem is that your dates are not in native mysql DATETIME format (%Y-%m-%d %H:%i:%s), this can be shown as such:
mysql> SELECT CAST('25/08/2016 02:00:00' AS DATETIME);
+-----------------------------------------+
| CAST('25/08/2016 02:00:00' AS DATETIME) |
+-----------------------------------------+
| NULL |
+-----------------------------------------+
1 row in set, 1 warning (0,00 sec)
mysql> SHOW WARNINGS;
+---------+------+-------------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------------+
| Warning | 1292 | Incorrect datetime value: '25/08/2016 02:00:00' |
+---------+------+-------------------------------------------------+
1 row in set (0,00 sec)
The solution is to get them into MySQL format, this could be done by manipulating your DATETIME column on disk or at source. This may be more difficult than the 'self sufficient' solution I'll outline below.
There exists the string to date (STR_TO_DATE) function to solve this kind of issue once data is inside the database, here is a demonstration with your format. Otherwise see the manual here. (See the DATE_FORMAT section for a table with the codes you can use for different date formats.):
mysql> SELECT CAST(STR_TO_DATE('25/08/2016 02:00:00', '%d/%m/%Y %H:%i:%s') AS DATETIME);
+---------------------------------------------------------------------------+
| CAST(STR_TO_DATE('25/08/2016 02:00:00', '%d/%m/%Y %H:%i:%s') AS DATETIME) |
+---------------------------------------------------------------------------+
| 2016-08-25 02:00:00 |
+---------------------------------------------------------------------------+
1 row in set (0,00 sec)
Personally in this situation I'd load the data into a temporary table that accepted the date fields as a string and then use an INSERT with the STR_TO_DATEfunction to get the data into the final table. A final solution (untested, guideline only) would look like this:
CREATE TEMPORARY TABLE valsLoad (DATETIME TEXT,NAME TEXT,ID TEXT,VAL INT);
LOAD DATA LOCAL INFILE 'vals.csv'
INTO TABLE valsLoad
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
IGNORE 1 LINES
(#varTimeSt,NOMINAL,NAME,ID,VAL) SET DATETIME = STR_TO_DATE(#varTimeSt,'%d/%m/%Y %h:%i:%s');
INSERT INTO vals
SELECT STR_TO_DATE(DATETIME, '%d/%m/%Y %H:%i:%m'), NAME, ID, VAL FROM valsLoad;
DROP TEMPORARY TABLE valsLoad;
Please let me know if you have any questions.
Regards,
James

Related

How can i change SQL date format to: 12th Jun 2021. (as example)

So, I'm trying to insert data from .csv file, but because of the date format I'm using - import causes it to set to 00-00-0000
import settings:
format - CSV using load data (otherwise it causing errors and failing to import)
Specific format options: none
Errors I'm receiving after import:
Data truncated for column...
my_date sets to 0000-00-00, even with 'DD/MMM/yyyy' date format,
my csv file structure: (just in case if i need to use specific format)
name;1;1st Jan 2021;2st Jan 2021;;;;;;;;;;;;;
Technically, I could format it manually to 12 jun 2021 / 12.06.2021 / 12/06/2021 but I would like to avoid that.
Sorry if it's a dumb question and the answer is simple, but I have no idea how to fix it. :)
I already tried this but still nothing.
SET lc_time_names = 'en_US';
select date_format(my_date, 'DD MMM yyyy') FROM table1;
select date_format(my_date, 'DD/MMM/yyyy') FROM table1;
Maybe you should import your date columns as text data type, and make transformations later! Please follow this steps:
Import Wizard
Then Update your columns:
UPDATE myimport
SET StartDate = STR_TO_DATE(StartDate,'%D %b %Y');
UPDATE myimport
SET FinishDate = STR_TO_DATE(FinishDate,'%D %b %Y');
Then Change data type to DATE(or preferably date time):
ALTER TABLE myimport
MODIFY COLUMN StartDate DATE,
MODIFY COLUMN FinishDate DATE;
If we check the data,
mysql> SELECT * FROM myimport;
+------+------+------------+------------+
| name | Row | StartDate | FinishDate |
+------+------+------------+------------+
| name | 1 | 2021-01-01 | 2021-01-02 |
+------+------+------------+------------+
1 row in set (0.00 sec)
If we check the datatype to ensure that It is date:
SHOW CREATE TABLE myimport;
+----------+------------------------------------------------------
| Table | Create Table |
+----------+------------------------------------------------------
| myimport | CREATE TABLE `myimport` (
`name` text,
`Row` int DEFAULT NULL,
`StartDate` date DEFAULT NULL,
`FinishDate` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------+------------------------------------------------------
1 row in set (0.00 sec)
You can transform and use the below query to transform the date.
select date_format(`created_at`, '%D %b %Y') FROM product_attributes;
Please see this pic for the query result.
You can use this SQL query to see the DB table query and insert query and use this for reference.

Issue with mysql time converstion

I am trying to read a file to mysql database, there is time column format like this
05/20/16 01:54:52.797 AM => month/day/year hours:minutes:seconds.millisecond AM/PM
I am using the following code by I can't read it corrrectly
Drop table temp;
CREATE TABLE temp LIKE messages;
load data infile 'C:/xampp/htdocs/gdxg/test_uploads/test.txt' into table temp fields terminated by '\t' enclosed by '"' lines terminated by '\n' (#Time, State, Name,Pri,Value,)
SET Time = STR_TO_DATE(#Time,'%m/%d/%y %H:%i:%s.%f');
select * from temp limit 10;
It doesn't read AM/PM
and if I tried to do so (#Time,'%m/%d/%y %H:%i:%s.%f %p) just read null?
You have used hour specifier wrongly.
Specifier descriptions:
'%H' - for hours in range (00..23)
'%h' - for hours in range (01..12)
'%p' - for AM or PM
Change H to h in your query and use of '%p' should be working.
Example:
mysql> select #t;
+--------------------------+
| #t |
+--------------------------+
| 05/20/16 01:54:52.797 AM |
+--------------------------+
1 row in set (0.00 sec)
mysql> select STR_TO_DATE( #t,'%m/%d/%y %h:%i:%s.%f %p' ) as t;
+----------------------------+
| t |
+----------------------------+
| 2016-05-20 01:54:52.797000 |
+----------------------------+
1 row in set (0.00 sec)
Read Documentation:
DATE_FORMAT(date,format)

Different values for datetime, date and time fields from timestamp in MySQL

I am trying to convert a TIMESTAMP to the DATETIME, DATE and TIME MySQL types using the FROM_UNIXTIME field. I noticed that the values for TIME and DATETIME fields have different time information on them.
Instead of the insert statement to the table, I am replacing it with a simple select statement that prints the values:
select FROM_UNIXTIME('1468561341') as timestamp_datetime,FROM_UNIXTIME('1468561341','%d/%m/%y') as timestamp_date, FROM_UNIXTIME('1468561341','%h:%m:%s %p') as timestamp_time
The results look like this:
timestamp_datetime: 2016-07-15 05:42:21.000000
timestamp_date 15/07/16
timestamp_time 05:07:21 AM
How can I get consistent time value in both these columns?
the issue is with letter m
it should be i
mysql> select FROM_UNIXTIME(1468561341) as timestamp_datetime,FROM_UNIXTIME(1468561341,'%d/%m/%y') as timestamp_date, FROM_UNIXTIME(1468561341,'%h:%i:%s %p') as timestamp_time;
+---------------------+----------------+----------------+
| timestamp_datetime | timestamp_date | timestamp_time |
+---------------------+----------------+----------------+
| 2016-07-15 05:42:21 | 15/07/16 | 05:42:21 AM |
+---------------------+----------------+----------------+
1 row in set (0.05 sec)
Your problem is that in your FROM_UNIXTIME you are essentially telling it to do
hours-months-seconds -AM/PM
But you want
hours-minutes-seconds -AM/PM
So change it to
FROM_UNIXTIME(1468561341,'%h:%i:%s %p')
instead.
Reference guide for all the time parameters and usage of time functions in MySQL here: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

MySQL CSV import: datetime value

I have been banging my head against a wall trying to import datetime values from a .csv file.
Here's the import statement.
LOAD DATA LOCAL INFILE 'myData.csv'
INTO TABLE equity_last_import
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(equity,last,#last_date)
SET last_date = STR_TO_DATE( #last_date, '%Y-%m-%d %H:%i:%s')
Here's a sample of the data:
4108,48.74,"2013-09-16 16:15:04"
4249,8.1,"2013-09-16 16:15:04"
4197,3.81,"2013-09-16 17:20:00"
4139,26.81,"2013-09-16 16:15:04"
4218,24.83,"2013-09-16 17:20:00"
4260,79.72,"2013-09-16 16:15:04"
4270,450.12,"2013-09-16 17:20:00"
4242,30.38,"2013-09-16 16:15:04"
4193,1.42,"2013-09-16 16:15:04"
4134,3.77,"2013-09-16 16:15:04"
I am able to import date values using STR_TO_DATE() but I not able to get datetime values to import. I have tried several different date formats other than '%Y-%m-%d %H:%i:%s' and I always get a null datetime [0000-00-00 00:00:00]. I have also tried not using STR_TO_DATE(), since the string is in the default MySQL datetime format.
Any help will be appreciated.
I ran into the same problem. I fixed it by changing the format for the date column in my CSV file to match the MySQL datetime format.
Open CSV in Excel.
Highlight the column.
Right-click on the column.
Click on Format Cells.
Pick Custom.
Use yyyy/mm/dd hh:mm:ss in the Type field.
Click ok
My CSV successfully imported after I changed the datetime format as above.
The date in your data file is already in a format MySQL should natively understand. It's just enclosed in double quotes. You need to tell LOAD DATA INFILE how to deal with the quotes. Try something like this:
LOAD DATA LOCAL INFILE 'myData.csv'
INTO TABLE equity_last_import
FIELDS OPTIONALLY ENCLOSED BY '"' TERMINATED BY ','
LINES TERMINATED BY '\n'
(equity,last,last_date)
Update:
Since you've said it doesn't work, I created a test table and verified that it does work. Here's the proof:
I've highlighted your csv data from the question and pasted into a new file called myData.csv in my system's /tmp folder. Then I connected to the mysql console, switched to the test database and ran the following:
mysql> create table equity_last_import (equity int, last decimal(10,2), last_date datetime) engine=innodb;
Query OK, 0 rows affected (0.02 sec)
mysql> LOAD DATA LOCAL INFILE '/tmp/myData.csv'
-> INTO TABLE equity_last_import
-> FIELDS OPTIONALLY ENCLOSED BY '"' TERMINATED BY ','
-> LINES TERMINATED BY '\n'
-> (equity,last,last_date);
Query OK, 10 rows affected (0.00 sec)
Records: 10 Deleted: 0 Skipped: 0 Warnings: 0
mysql> select * from equity_last_import;
+--------+--------+---------------------+
| equity | last | last_date |
+--------+--------+---------------------+
| 4108 | 48.74 | 2013-09-16 16:15:04 |
| 4249 | 8.10 | 2013-09-16 16:15:04 |
| 4197 | 3.81 | 2013-09-16 17:20:00 |
| 4139 | 26.81 | 2013-09-16 16:15:04 |
| 4218 | 24.83 | 2013-09-16 17:20:00 |
| 4260 | 79.72 | 2013-09-16 16:15:04 |
| 4270 | 450.12 | 2013-09-16 17:20:00 |
| 4242 | 30.38 | 2013-09-16 16:15:04 |
| 4193 | 1.42 | 2013-09-16 16:15:04 |
| 4134 | 3.77 | 2013-09-16 16:15:04 |
+--------+--------+---------------------+
10 rows in set (0.00 sec)
See? It works perfectly.
Another Update:
You've specified that you're getting the following error now:
Out of range value for column 'last_date' at row 1
Does your CSV file have a header? If so, you may want to add IGNORE 1 LINES to your LOAD DATA INFILE command to tell MySQL to skip over the header.
Pulled my hair out over this also because I'm not importing in the above suggested way.
Workaround: Created a temporary field temp_date of type "VARCHAR" on your import table and have no problems loading the data. I then was able to perform an update on my date column which is of type date.
update table
set date = temp_date
I was having the same trouble and here's what I discovered, I think it might help you
The problem regards a GMT conflict:
The database I was extracting the .csv file was on GMT 00:00, so there wasn't daylight saving time.
My local server (which was the one I was trying to insert the .csv file) was running on my computer (system's) GMT, by default. In my case it was GMT -3, which is affected by daylight saving time.
SQL has a special way to deal with daylight saving time, it ignores the exact date and time when the daylight saving time starts to happen. In my case, it was october 20 and all the records between 00 and 1 AM of that day simply weren't recognized by the server, even if the format was correct, because they simply 'didn't exist' (see more here). This was affecting all timestamp records, not only the specifics of daylight saving time.
My solution was to set the local server to GMT +00, before creating the new table and import the .csv, using
SET time_zone='+00:00';
And then when I imported the .csv file all the records were read properly. I think if you set the time zone equal to the one that generated the .csv file should work!
Open CSV in Excel.
Highlight the column.
Right-click on the column.
Click on Format Cells.
Pick Custom.
Use same format as SQL date format yyyy-mm-dd
Click ok and save
it's working fine for me

Load data from CSV inside bit field in mysql

What's the right syntax to insert a value inside a column of type bit(1) in `MySQL'?
My column definition is:
payed bit(1) NOT NULL
I'm loading the data from a csv where the data is saved as 0 or 1.
I've tried to do the insert using:
b'value' or 0bvalue (example b'1' or 0b1)
As indicated from the manual.
But I keep getting this error:
Warning | 1264 | Out of range value for column 'payed' at row 1
What's the right way to insert a bit value?
I'm not doing the insert manually but I'm loading the data from a csv (using load data infile) in which the data for the column is 0 or 1.
This is my load query, I've renamed the fields for privacy questions, there's no error in that definition:
load data local infile 'input_data.csv' into table table
fields terminated by ',' lines terminated by '\n'
(id, year, field1, #date2, #date1, field2, field3, field4, field5, field6, payed, field8, field9, field10, field11, project_id)
set
date1 = str_to_date(#date1, '%a %b %d %x:%x:%x UTC %Y'),
date2 = str_to_date(#date2, '%a %b %d %x:%x:%x UTC %Y');
show warnings;
This is an example row of my CSV:
200014,2013,0.0,Wed Feb 09 00:00:00 UTC 2014,Thu Feb 28 00:00:00 UTC 2013,2500.0,21,Business,0,,0,40.0,0,PROSPECT,1,200013
Update:
I didn't find a solution with the bit, so I've changed the column data type from bit to tinyint to make it work.
I've finally found the solution and I'm posting it here for future reference. I've found help in the mysql load data manual page.
So for test purpose my table structure is:
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| nome | varchar(45) | YES | | NULL | |
| valore | bit(1) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
My csv test file is:
1,primo_valore,1
2,secondo_valore,0
3,terzo_valore,1
The query to load the csv into the table is:
load data infile 'test.csv' into table test
fields terminated by ',' lines terminated by '\n'
(id, nome, #valore) set
valore=cast(#valore as signed);
show warnings;
As you can see do load the csv you need to do a cast cast(#valore as signed) and in your csv you can use the integer notation 1 or 0 to indicate the bit value. This is because BIT values cannot be loaded using binary notation (for example, b'011010').
Replace the "0" values in the csv by no value at all. That worked for me.
You can use BIN() function like this :
INSERT INTO `table` VALUES (`column` = BIN(1)), (`column` = BIN(0));
Let me guess, but I think you should ignore 1st line of your CSV file in LOAD query.
See "IGNORE number LINES"