I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.
Related
I have some data in the following date format.
'27-SEP-97' i.e DD-MON-YY
Now I want to convert this to YYYYMMDD. I am using the following script to convert this.
TO_CHAR(TO_DATE(CHD_DATE_FIRST_ACT,'DD-MON-YY'),'YYYYMMDD')
but this is giving me the following output.
20970927
I want this data to be in YYYYMMDD format, such that the output looks like this- 19970927
If '27-SEP-97' is a string (which is what your words suggest), then such a combination of TO_this and TO_that might do the job:
SQL> with test as (select '27-SEP-97' datum from dual)
2 select to_char(to_date(datum, 'dd-mon-rr', 'nls_date_language = english'), 'yyyymmdd') result
3 from test;
RESULT
--------------------------------------------------------------------------------
19970927
SQL>
--USE RR instead of YY in your query.
select TO_CHAR(TO_DATE('27-SEP-97','DD-MON-RR'),'YYYYMMDD') from dual;
You can make use of mysql replace and str_to_date functions
replace takes 3 arguments as show below
replace(string,find_string,replace_with)
you should simply replace - with a blank string
if your str is '27-SEP-97' to get the output as 19970927 execute the following in mysql
select replace(str_to_date('27-SEP-97','%d-%b-%Y'),'-','') as date;
output
+----------+
| date |
+----------+
| 19970927 |
+----------+
%b is used to mention abbreviated month name
click the below links to know more about mysql date and time functions
Mysql Data and Time functions
I want to convert '01-Dec-2015' date to '2015-12-01'.
how i can do this in mysql.
When I am executing my query:-
SET SQL_SAFE_UPDATES=0;
UPDATE biometric_date
SET att_date = STR_TO_DATE(att_date, '%d/%m/%Y');
It show me error like
Error Code: 1411. Incorrect datetime value: '01-Dec-2015' for function str_to_date
Please help me
UPDATE biometric_date SET att_date = STR_TO_DATE('01-Dec-2015','%d-%M-%Y')
Just put current format as second parameter in STR_TO_DATE() function:
UPDATE date_table t SET att_date = STR_TO_DATE(t.att_date,'%d-%M-%Y');
You should do something like:
mysql> select str_to_date('01-Dec-2015','%d-%M-%Y');
+---------------------------------------+
| str_to_date('01-Dec-2015','%d-%M-%Y') |
+---------------------------------------+
| 2015-12-01 |
+---------------------------------------+
1 row in set (0,01 sec)
Check your att_date. This might not be in required format.
You can also use DATE_FORMAT
SELECT DATE_FORMAT('01-Dec-2015','%d-%m-%Y') as somecolname
FROM tablename
I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.
I'm working on a site that requires me to display a graph of the average number per day of a user input. I have a SQL query already that returns this info to me:
SELECT sum(number)/count(number) as average, date FROM stats WHERE * GROUP BY date
This gives me the result I am looking for, but the result is given with three decimals precision. I want to round of this number. I could do it in PHP or my template engine, of course, but I was curious if there was a way to do this all in the database.
Is there a way to cast an output as an integer (in MySQL)?
SELECT
CAST(sum(number)/count(number) as UNSIGNED) as average,
date
FROM stats
WHERE *
GROUP BY date
The valid types for a CAST in MySQL are as follows
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
So you could use
SELECT CAST(sum(number)/count(number) AS UNSIGNED) as average...
Or SIGNED if the SUM part can ever add up to a negative number.
Use the DIV operator.
mysql> SELECT 5 DIV 2;
-> 2
Integer division. Similar to FLOOR(), but is safe with BIGINT values. Incorrect results may occur for noninteger operands that exceed BIGINT range.
how about using MySQL FORMAT Function?
mysql> SELECT FORMAT(12345.123456, 4);
+-------------------------+
| FORMAT(12345.123456, 4) |
+-------------------------+
| 12,345.1235 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT FORMAT(12345.123456, 0);
+-------------------------+
| FORMAT(12345.123456, 0) |
+-------------------------+
| 12,345 |
+-------------------------+
1 row in set (0.00 sec)
SELECT convert(int, sum(number)/count(number)) as average,
date
FROM stats
WHERE * GROUP BY date
or
SELECT
CAST(sum(number)/count(number) as INT) as average,
date
FROM stats
WHERE *
GROUP BY date
User mysql function round()
Example round(23.33) will return 23 in msyql.
Your example query will be updated to
SELECT round(sum(number)/count(number)) as average, date FROM stats WHERE * GROUP BY date
Not sure really where to start with this one. Can anyone help/point me in the right direction.
I have a timestamp column in MySQL and I want to select a date range for example, all timestamps which are in Oct 2010.
Thanks.
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE and post data wild character search. Hopefully this will solve your problem.
SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'
This SQL query will extract the data for you. It is easy and fast.
SELECT *
FROM table_name
WHERE extract( YEAR_MONTH from timestamp)="201010";
Whenever possible, avoid applying functions to a column in the where clause:
SELECT *
FROM table_name
WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00')
AND timestamp < UNIX_TIMESTAMP('2010-11-01 00:00:00');
Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.
If you have a mysql timestamp, something like 2013-09-29 22:27:10 you can do this
select * from table WHERE MONTH(FROM_UNIXTIME(UNIX_TIMESTAMP(time)))=9;
Convert to unix, then use the unix time functions to extract the month, in this case 9 for september.