Format the date and time in MySQL default format - mysql

I have a MySQL table with forex tick data
pair tick_date_time price_low price_high
------- --------------------- --------- ------------
USD/JPY 20091201 00:00:00.628 86.280000 86.286000
USD/JPY 20091201 00:00:00.722 86.280000 86.289000
USD/JPY 20091201 00:00:00.741 86.281000 86.289000
USD/JPY 20091201 00:00:01.130 86.283000 86.289000
USD/JPY 20091201 00:00:01.131 86.283000 86.289000
The date/time in this table is not formatted in MySQL default format. I use the query to format the data
SELECT DATE_FORMAT(t.tick_date_time, "%Y%m%d %H:%i:%s") FROM table AS t
This returns NULL. Any idea where I'm wrong? I also like to extract milliseconds if possible.

You are looking for the function str_to_date(), not date_format():
SELECT str_to_date(t.tick_date_time, '%Y%m%d %H:%i:%s')
date_format() takes a date and produces a string. str_to_date() takes a string and converts it to a date.

Related

How to parse time of ISO timestamp in mysql?

How can a ISO datetime String timestamp be correctly parsed to time type column in mysql? I noticed the following:
select CAST('2013-09-05T10:10:02' as time) from mytable limit 1
Result incorrect:
00:20:13
select CAST(CAST('2013-09-05T10:10:02' as datetime) as time) from mytable limit 1
Result correct:
10:10:02
Why do I have to make a double CAST here to get the correct time? And more important: how is time parsing done property?
Because you have a string which you need to first cast it into date format.
If you cast it in time like below:
select CAST('2014-09-05T10:10:02' as time)
00:20:14
select CAST('2015-09-05T10:10:02' as time)
00:20:15
select CAST('2013' as time) --below casting string as time
00:20:13
If you monitor closely its treating it as string and getting year as time.
So you need to cast it datetime first then time.
select CAST(CAST('2013-09-05T10:10:02' as datetime) as time)
Basically when you try to convert something to a time that looks like an integer MySQL treats that as something in the form HHMMSS, so your 2013-09-05T10:10:02 becomes 00:20:13. To convert properly, the value needs to be a MySQL datetime, which you can do via CAST or you can use STR_TO_DATE to convert your date string to a MySQL date, then TIME to extract the time part of it:
SELECT TIME(STR_TO_DATE('2013-09-05T10:10:02', '%Y-%m-%dT%H:%i:%s'))
Output:
10:10:02
Demo on dbfiddle

SQL STR_TO_DATE

I'm having trouble with the following code:
INSERT into `fun` ( funner)
SELECT YEAR(STR_TO_DATE(SUBSTRING(time,1,4), '%Y'))
FROM `orig`
returning the warning:
Incorrect datetime value: '1880' for function str_to_date
time is a varchar column in the table orig with the format yyyy/mm.
I want to extract the year section from this varchar and translate it into a year datatype using STR_TO_DATE
I would recommend using one of the usual date and time MySQL datatypes, instead of the rarely used YEAR datatype : DATE, DATETIME and TIMESTAMP.
If you want to turn your string to a date datatype, then :
STR_TO_DATE(my_column, '%Y/%m')
You can use the YEAR() function on this date, and it will return an integer value :
YEAR(STR_TO_DATE(my_column, '%Y/%m'))
Finally : if all you want is get the year from a date stored as string, then you can directly extract it the string using SUBSTR :
SUBSTR(my_column, 1, 4)
This returns a string (not an integer), that MySQL will implictely convert to a number when used in numeric context.
You can convert SUBSTRING(time,1,4) to integer:
SELECT CONVERT(SUBSTRING(time,1,4),UNSIGNED INTEGER) FROM orig
there is no need to convert it first to a date and then convert to integer.
I guess you need to return an integer value since you use the YEAR() function.
If not a simple SELECT SUBSTRING(time,1,4) FROM orig will do.
What does time look like? If year has the data type year, then you can insert a date into the column:
INSERT into `clean` (year)
SELECT DATE(CONCAT(SUBSTRING(time, 1, 4), '-01-01'))
FROM `orig` ;
I am not a fan of the year data type. You should just put the entire date into the column.

SQL Change date format from yyyy-mm-dd to dd-mm-yyyy

I have created MySQL table :
CREATE TABLE EMP(
EMPID INTEGER NOT NULL (5),
SURNAME VARCHAR(25),
SAL INTEGER(5),
JON VARCHAR(25),
START_DATE DATE,
END_DATE DATE,
DEPNO INTEGER(5)
);
with following records:
INSERT INTO EMP
(EMPID,SURNAME,SALARY,JOB,START_DATE,END_DATE,DEPNO)
VALUES
('1','Vorosila','500000','COO','20150101',null,'1');
however I need to change date format from 2015 01 01 to 01 01 2015
Can anybody show me or tell me how to do that ?
THANK YOU IN ADVANCE
DATE values do not have a "format", they are objects that represent instants in time (or entire days, but still independent of formatting).
Formats are applied on input and output, so you just need to apply the correct format, which you can find in the MySQL manual, to the SELECT statement.
You cannot change the default date format in mysql.
I once hoped for the default date to be editable so I wouldn't have to jump through these hoops to get the date I actually wanted, mysql even has a date format system variable, but it is unused. Date Format Mysql - link
What you should really do is store it as the default format Year-Month-Date and then convert it on select.
The first thing I'd suggest is having your date columns as date types, which would give your dates the following format '2015-01-01'.
If you do this then you can use DATE_FORMAT - link - the second value in the DATE_FORMAT function allows you to customise the returned date, and there are many different thing you can do with this if you look at the link:
SELECT
DATE_FORMAT(`START_DATE`,'%d-%m-%Y')
AS `START_DATE`
FROM ...
The other option you have is to store your dates in the format that you already want as a char or varchar column.
HOWEVER, as should be obvious, this column will not be treated as storing dates, and so will not give you the correct comparisons in a where clause when using > < BETWEEN or the correct ordering in an order by clause. It is after all just a string of numbers in this case.
However you can then use STR_TO_DATE - link if you did need to use a where or order by on this column to change it back to a date within the query - in this case the second value is the custom format of your 'dates' in the column. Keep in mind with a where you will need to compare it with the correct mysql format as shown below:
SELECT
`START_DATE`
FROM table
WHERE STR_TO_DATE(`START_DATE`,'%d-%m-%Y') BETWEEN '2015-01-01' and '2016-01-01'
In MySQL you can change the format of a date using DATE_FORMAT method which is similar to to_char in Oracle.
DATE_FORMAT(SYSDATE(), '%DD-%MM-%YYYY');
For more information about specifiers check this thread http://www.sqlines.com/oracle-to-mysql/to_char_datetime
You can do what you probably want by creating a view and referring to that instead of the (underlying) table.
CREATE VIEW emp_view AS
SELECT empid,
surname,
sal,
jon,
date_format(start_date, '%d-%m-%Y') as start_date,
date_format(end_date, '%d-%m-%Y') as end_date,
depno
FROM emp;
Note that this changes the type of the date columns to varchar, so comparisons will no longer work as expected:
SELECT * FROM emp_view WHERE start_date > '01-12-1924'; // fails!

How to select latest date from database in MySQL

I have list of date in MySQL in the format of "MM-DD-YYYY" and When I was trying to fetch the latest date from table it just return the last date of a Year like 12-01-2014 instead of return latest date 03-16-2016.
Payment history table:
to_date
03-16-2016
12-01-2014
11-07-2014
10-03-2014
01-09-2014
I used following query:
SELECT MAX(to_date) FROM paymenthistory WHERE empid=59;
Result : 12-01-2014
Related post: Get the latest date from grouped MySQL data
Thanks in advance
You're working with strings, not native dates, so you're getting the maximum date.
Either convert those strings to ACTUAL mysql date/datetime values, or you'll have to go with ugly hacks, like
SELECT MAX(STR_TO_DATE(to_date, '%m-%d-%Y'))
and performance will be massively bad. MySQL's native date format is yyyy-mm-dd hh:mm:ss, which is a natural "most significant first" format. If your date strings were formatted like that, then even a max(string) would work.
It sounds like your date column is actually a VARCHAR format since it is seeing 12-01-2014 as the last date which is only true if stored as a VARCHAR.
Be sure your to_date column is a DATE type.
have you tried this?
SELECT TOP 1 * FROM paymenthistory WHERE empid = 29 ORDER BY to_date DESC;
For mysql try this
SELECT * FROM paymenthistory WHERE empid=59 ORDER BY to_date DESC LIMIT 1;

Change datatime to date dd/mm/yy

Im trying to query some data and one of them is a datetime format. I want that is shows dd/mm/yy with no time on it directly form the select. Is this possible?
My query is and the join_date is datetime that i need to be changed to short date:
$query = mysql_query("SELECT id,username,join_date,is_active FROM members",$con)
or trigger_error(mysql_error());
This query goes directy in a Json output array. So i want to convert it directy form the query.
Use the MySQL DATE_FORMAT function for this:
SELECT id, username, DATE_FORMAT(join_date, '%d/%m/%y') AS join_formatted, is_active
FROM members
In this example, the column name for the formatted date will be join_formatted, and its type will be VARCHAR.
The format string returns the date as dd/mm/yy as requested, but I'm personally more comfortable when the date includes the full century. To get the full century, use uppercase Y in the format string: %d/%m/%Y.
try this :
"SELECT id, username, DATE_FORMAT(join_date,'%d/%m/%y'), is_active FROM members"
Use DATE_FORMAT:
SELECT id, username, DATE_FORMAT(join_date, "%d/%m/%y") AS date FROM members;
%Y Year, numeric, four digits
%y Year, numeric (two digits)
For details about date format link