MySQL date converstion - mysql

I have a table in MySQL, where I have a date and time column. Where format of this column is 01 February 2013 12:49:40. I want to extract the date part and time part as well as month part also. I am using month(01 February 2013 12:49:40) this function but it's throwing error. I can't use the Substring, as the width of the row is not equal. What should I do.

First convert it to a real date (what you have is just text, MySQL doesn't know it's a date)
SELECT STR_TO_DATE(your_column, '%d %M %Y %H:%i:%s')
then you can use functions like year(), month(), time(), whatever to get what you want...
SELECT YEAR(STR_TO_DATE(your_column, '%d %M %Y %H:%i:%s')) FROM your_table...
Even better would be of course, to change the column to datatype datetime or timestamp. Then you could spare yourself the STR_TO_DATE() function every time.
Do so by adding a column datetime or timestamp to your table
ALTER TABLE your_table ADD COLUMN your_column datetime;
Then "copy" your column with
UPDATE yourTable SET new_column = STR_TO_DATE(old_column, '%d %M %Y %H:%i:%s');
Then you can drop your current column.
ALTER TABLE DROP COLUMN your_current_column;
Or choose another approach, several possibilities...

Related

Sort by varchar date entry in SQL

I want to sort my table by DATE which is a varchar holding date information like this:
January 06, 2023 // format is Month Day, Year
I want to sort by date but it doesn't work since this is not datetime. I've tried casting DATE but it doesn't seem to work. I tried like this:
SELECT * FROM receipt WHERE ID=? ORDER BY CAST(DATE AS datetime) DESC
I also tried convert but it did not work either, I must be using the syntax wrong.
How can I sort by date if my DATE entry is of type varchar.
In MySQL you can use str_to_date with the appropriate date format to convert a varchar to a date:
SELECT * FROM receipt WHERE ID=? ORDER BY STR_TO_DATE(date, '%M %d, %Y') DESC

How to convert text datatype to datetime in mysql?

In mysql database,column name created.This "created " column is text datatype,I need to change this to datetime.Now this column have so many datas.Is it possible to convert it or?
Database look like
created
18-11-15 18:21:25
Expecting ouput is
created
2018-11-15 18:21:25
When am doing
ALTER TABLE invoices MODIFY created datetime
This query giving wrong data.its converting from 15-09-18 03:03:43 to 2015-09-18 03:03:43
If the original data is not in MySQL Datetime format (YYYY-MM-DD HH:MM:SS), you cannot just change the column datatype from Varchar/Text to Date/Datetime. Otherwise, there will be an irreparable Data loss.
This will be a multi-step process. You will first need to convert the date string to MySQL date format (YYYY-MM-DD HH:MM:SS). We can use STR_TO_DATE() function for this.
Your sample date string (18-11-15 18:21:25) is basically in %y-%m-%d %T format. Following format specifiers can be used:
%d Day of the month as a numeric value (01 to 31)
%m Month name as a numeric value (00 to 12)
%y Year as a numeric, 2-digit value
%T Time in 24 hour format (hh:mm:ss)
The query to update the date would look as follows:
UPDATE invoices
SET created = STR_TO_DATE(created, '%y-%m-%d %T');
Now, you can use Alter Table to change the data type from Text type to Datetime.
ALTER TABLE invoices
MODIFY COLUMN created datetime;
The best thing to do here is to not store your dates as text. Assuming you have already done this, we can cope by calling STR_TO_DATE to generate a bona fide date:
SELECT
STR_TO_DATE(created, '%y-%m-%d %h:%i:%s') AS created_out
FROM yourTable;
Since the output you expect is standard date output, we can stop here and avoid also calling DATE_FORMAT to generate a different output.
you want to convert output or database records ? for second you can use sql query :
UPDATE 'table_name' SET 'created' = CONCAT('20', 'created')
You will need first to interchange the day with the year in the created column, as follows:
UPDATE invoices
SET created = CONCAT(SUBSTR(created, 7, 2), '-', SUBSTR(created, 4, 2), '-', SUBSTR(created, 1, 2));
Then, you convert the column to DATETIME, as follows:
ALTER TABLE invoices MODIFY created DATETIME;
Hope this helps.

Make a query that will get a specific month from my sales table

In my sales table have the date column and the date is formatted like this January 9, 2018, 5:06 pm. How can I specifically get all the sales made from the month of January 2018 using MySQL?
assuming you date column is a date data type columns you can use year() and month() function
select * from my_table
where year(my_date_col) = 2018
and month(my_date_col) = 1
Since
the date is formatted like this January 9, 2018, 5:06 pm
and this is not recognizable time format for MySQL I belive the solution is:
SELECT * FROM table WHERE date like 'January%2018%';
I know this is not a "best practice" as well as storing time in a wrong type.
Since the column isn't already in a DATE format, let's assume it has to stay in its current format for the application purposes and add an auxiliary DATE column to select on (because SELECTs will be more optimized this way).
First we add a VIRTUAL column (requires MySQL 5.7+), which is a calculated column that is calculated at runtime but not stored on disk. We don't need to store this column on disk because we're going to index it later. Our VIRTUAL column will convert the application date's format to a MySQL DATE.
Replace str_date with your current date column:
ALTER TABLE `my_table`
ADD `virtual_date` DATETIME AS (STR_TO_DATE(`str_date`, '%M %d, %Y, %l:%i %p')) VIRTUAL AFTER `date`;
Now add the INDEX:
ALTER TABLE my_table ADD INDEX (`virtual_date`);
Now we can perform a properly indexed SELECT:
SELECT *
FROM my_table
WHERE virtual_date >= '2018-01-01'
AND virtual_date <= '2018-01-31'
or
SELECT *
FROM my_table
WHERE virtual_date >= '2018-01-01'
AND virtual_date <= LAST_DAY('2018-01-01')
The MySQL DATE format is YYYY-MM-DD. The latter query is logically simpler; the LAST_DAY() function will give you the last DATE of the month given a DATE or DATETIME value.

How to use function with Table

I created a table in which i used timestamp column which tells the record is updated on that time and date.
create table age_info (age tinyint not null,created_on timestamp not null );
But i want to change display like this.select date_format(Now() ,'%W, %e %M %Y # %r');
Tuesday, 31 July 2015 # 02:32:16 PM
But don't know how to do it. When i insert values
insert into age_info(age) values (19);
in the table it show like this.
age created_on
19 2015-07-31 18:55:01
I Don't know how to use this function date_format with timestamp column to show like that format.
I think this will help you to solve the answer
SELECT DATE_FORMAT(`created_on` , '%W, %e %b %Y # %r') FROM `age_info`;
To insert,
INSERT INTO `age_info` (`age`) select DATE_FORMAT(now() , '%W %e, %b %Y # %r')created_on from age_info
Note that, You need to change the table field to varchar.
You can keep the format you want by changing your column definition to a text column. Is that what you really want? You'll lose all the benefits a timestamp column offers (easy date and time calculations, etc).
You can't change the datetime column type to store the data as you want, it changes the meaning of the datetime and no advantage of it, although you can use it to select the format whatever you want using date_format() function.

How to convert and use varchar data type as a datetime in mysql

Hello all,
This is the format of my my-sql data type "rdate".
Apr 1 2011 01:13:00:000PM
I want to use the order by rdate and i can't make it right order as the data type of rdate is varchar, So i want to convert it to date time , But no success.
I am trying to use date_format(str_to_date(rdate, '%m/%d/%Y'), '%Y%m');
Thanks
Mypixel
Try doing:
ORDER BY str_to_date(rdate,'%M %d %Y %h:%i:%s')
From the docs:
Your Date is in the Following format:
%M Month name (January..December)
%d Day of the month, numeric (00..31)
%Y Year, numeric, four digits
...
You have to tell str_to_date the format that your string is in. This means the way the specific parts of the date are displayed, spaces, etc.
sqlfiddle demo
In your str_to_date function call, you need to specify what the format IS, not what you want it to be. Try this:
str_to_date(rdate, '%M %d %Y %h:%i:%s'));
UPDATE table SET rdate=str_to_date(rdate,'%M %d %Y %h:%i:%s')
Just convert your column for good to datetime.