I have a table with a date field, having human date in it like: '2008-01-08 19:23:32'
Now i have to copy this field plus some other fields of the same table to another table, but date needs to be in unix timestamp.
Is there any function in mysql which converts human date to unix timestamp inside query itself?
mysql> select unix_timestamp('2008-01-08 19:23:32');
+---------------------------------------+
| unix_timestamp('2008-01-08 19:23:32') |
+---------------------------------------+
| 1199849012 |
+---------------------------------------+
1 row in set (0.04 sec)
found here: http://www.epochconverter.com/
UNIX_TIMESTAMP() Should do the trick!
From MySQL Docs:
If called with no argument, returns a Unix timestamp (seconds since
'1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP()
is called with a date argument, it returns the value of the argument
as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string,
a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or
YYYYMMDD. The server interprets date as a value in the current time
zone and converts it to an internal value in UTC.
mysql> SELECT UNIX_TIMESTAMP();
-> 1196440210
mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
-> 1196440219
SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
Yes.
SELECT UNIX_TIMESTAMP(column) FROM TABLE
Query:
SELECT UNIX_TIMESTAMP(TIMESTAMP(`opened`)) as timestamp_date, `opened` as datetime_type FROM `myterminal`
Outputs:
| timestamp_date | datetime_type
|------------------- |---------------------
| 1536602012 | 2018-09-10 14:53:32
| 1536603854 | 2018-09-10 15:24:14
Related
I know that the code is incorrect and that the ADDDATE function should be used, but I'm trying to find out if a specific behaviour is caused by this bug.
So, does anyone know what exactly happens if I have the statement
SELECT * FROM MyTable WHERE TheTimestamp > (NOW()-86400);
when TheTimestamp is of the datetime data type?
It's not a bug. You're just expecting a datetime cast to a number to be something it's not.
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html says:
MySQL recognizes DATETIME and TIMESTAMP values in these formats:
...
As a number in either YYYYMMDDhhmmss or YYMMDDhhmmss format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html says:
MySQL automatically converts a date or time value to a number if the value is used in numeric context and vice versa.
So using NOW() in an arithmetic expression converts it to a number:
mysql> SELECT now(), now() + 0;
+---------------------+----------------+
| now() | now() + 0 |
+---------------------+----------------+
| 2022-10-19 14:13:14 | 20221019141314 |
+---------------------+----------------+
You can see this converts '2022-10-19 14:13:14' (the date and time I test this query) into an integer simply by removing the punctuation and whitespace. This isn't a number you can add or subtract with, because the values 60-99 aren't used for seconds or minutes, and likewise the values 24-99 for hours, 32-99 for days, 13-99 for months, etc.
The expression you showed doesn't produce a number that is valid as a timestamp:
mysql> SELECT now(), now() - 86400;
+---------------------+----------------+
| now() | now() - 86400 |
+---------------------+----------------+
| 2022-10-19 14:20:09 | 20221019055609 |
+---------------------+----------------+
^^ there is no time with 56 minutes
^^^^ yesterday's date should be 10/18
To do arithmetic on the datetime, you should either convert to a integer measure of seconds, then use that value in integer expressions:
mysql> SELECT now(), unix_timestamp(now());
+---------------------+-----------------------+
| now() | unix_timestamp(now()) |
+---------------------+-----------------------+
| 2022-10-19 14:16:57 | 1666214217 |
+---------------------+-----------------------+
Or else use MySQL's support for temporal INTERVAL expressions. See https://dev.mysql.com/doc/refman/8.0/en/expressions.html#temporal-intervals
mysql> select now(), now() - interval 86400 second;
+---------------------+-------------------------------+
| now() | now() - interval 86400 second |
+---------------------+-------------------------------+
| 2022-10-19 14:24:01 | 2022-10-18 14:24:01 |
+---------------------+-------------------------------+
DATETIME and TIMESTAMP values are implicitly integer values of 5 and 4 bytes in length respectively (with optional additional bytes for fractional seconds precision). Mathematical operators, as well as conditional operators, will work accordingly. However, this will not account for all the implicit conversions like when you use ADDTIME().
This operation specifically looks for any records created later than 1 day ago, since the DATETIME value has to be greater than (later in time) the current time - 86400 seconds (1 day/24 hours) ago.
I have DATETIME column in my table, with 2015-04-23 11:17:49 properties
Trying to convert it to unix timestamp, acording to the mysql documentation I need just put the field into UNIX_TIMESTAMP() function and I'll get -> 1223423442 - timestamp but it's doesn't work, I've got only 0000-00-00 00:00:00
Tried a lot of stuff:
// doesn't work
UNIX_TIMESTAMP(CAST(`updated` AS CHAR(100))) AS updated_at,
// doesn't work
UNIX_TIMESTAMP(`updated`) AS updated_at,
//doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(CAST(`created` AS CHAR(100)), \'%M %e %Y %h:%i%p\'))
AS created_at'
// doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(`created`, '%M %e %Y %h:%i%p'))
AS created_at
Without `` doesn't work as well, am I missing something?
Try:
select
o1.id,
o1.operation_date_time,
(unix_timestamp(o2.operation_date_time) - unix_timestamp(o1.operation_date_time))
as duration
from operations as o1
inner join operations as o2
where o1.operation = "START"
and o2.operation = "STOP"
and o1.id = (o2.id - 1);
It should give as output:
+------+---------------------+----------+
| id | operation_date_time | duration |
+------+---------------------+----------+
| 1 | 2000-01-01 06:30:45 | 4455 |
| 3 | 2000-01-01 08:18:12 | 11146 |
| 5 | 2000-01-01 15:45:01 | 11792 |
+------+---------------------+----------+
3 rows in set (0.00 sec)
I do not understand why do you need to convert DATETIME to TIMESTAMP.
You can use INT(11) field to store UNIX TIMESTAMPs converted from DATETIME using function UNIX_TIMESTAMP(your_datetime_field).
Note, according to documentation: http://dev.mysql.com/doc/refman/5.5/en/datetime.html
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
I have a table with a TIMESTAMP field (lastHonored).
I ran this query:
SELECT NOW(), lastHonored,
TIMESTAMPDIFF(SECOND, lastHonored, NOW()), NOW()-lastHonored
FROM db.table
I get the result:
NOW() | lastHonored | DIFF | SUBTRACT
2014-10-27 14:07:22 | 2014-10-26 19:49:51 | 65851 | 945771
Where DIFF is the result of the TIMESTAMPDIFF function, and SUBTRACT is the result of the NOW()-lastHonored expresssion.
DIFF looks right, but can anyone tell me what NOW()-lastHonored calculates? It is not the right order of magnitude, and I'm stumped.
One would think that NOW() returns a datetime or similar type. But no. For some historical reason, NOW() returns either a number or a string. To quote the documentation:
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'
or YYYYMMDDHHMMSS format, depending on whether the function is used in
a string or numeric context. The value is expressed in the current
time zone.
That means that NOW() gets converted to a value based on its context. The - suggests a numeric context, so NOW() is a number whose digits are YYYYMMDDHHMMSS. My guess is that lastHonored gets similarly converted, so the result is the difference between two numbers.
You can see why by running:
SELECT CAST(NOW() AS UNSIGNED), CAST('2014-10-26 19:49:51' AS UNSIGNED);
By doing simple subtraction, MySQL is turning both values into numbers. NOW() the DATETIME becomes 20141027141923, but 2014-10-26 19:49:51 the STRING becomes 2014.
If you first cast the date to a DATETIME it gives you results more along the lines of what you expect:
SELECT CAST(NOW() AS UNSIGNED), CAST(CAST('2014-10-26 19:49:51' AS DATETIME) AS UNSIGNED);
You can't subtract dates like you are with NOW()-lastHonored. Dates/datetimes are not directly "subtractable":
MariaDB [test]> select '2014-10-27 08:18:00' - '2014-10-27 08:17:00';
+-----------------------------------------------+
| '2014-10-27 08:18:00' - '2014-10-27 08:17:00' |
+-----------------------------------------------+
| 0 |
+-----------------------------------------------+
1 row in set, 2 warnings (0.00 sec)
MariaDB [test]> show warnings;
+---------+------+---------------------------------------------------------+
| Level | Code | Message |
+---------+------+---------------------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:18:00' |
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:17:00' |
+---------+------+---------------------------------------------------------+
2 rows in set (0.00 sec)
Note the warnings. You'll get results, but they almost always be totally useless/incorrect results, because MySQL is casting the date values as doubles.
They do different things, substraction does not take into account that you are dealing with times.
If you do:
SELECT NOW(), lastHonored,
TIMESTAMPDIFF(SECOND, lastHonored, NOW()) THE_DIFF, NOW()-lastHonored THE_SUBSTRACTION,
NOW()+0 NOW_NUMBER_REPRESNTATION,
lastHonored+0 lastHonored_NUMBER_REPRESENTATION
FROM db.table
You will see the numeric difference is represented with the substraction and the time differente with TIMESTAMPDIFF.
I have two columns in MySQL database.
One is in DATE format like 2014-01-26, another one is in DATETIME format: 2014-01-25 17:19:07.
I need to apply TIMEDIFF(2014-01-26, 2014-01-25 17:19:07) function, but it requires both variables are in DATETIME format. How can I convert 2014-01-26 to 2014-01-26 00:00:00?
You can always cast a Date to a datetime
select timediff(cast(<yourDateColumn> as Datetime), <yourDatetimeColumn>)
But I'm not even really sure that you need to cast (depending on your mysql version), I may misunderstand the doc, but we can read
Prior to MySQL 5.1.18, when DATE values are compared with DATETIME
values, the time portion of the DATETIME value is ignored, or the
comparison could be performed as a string compare. Starting from MySQL
5.1.18, a DATE value is coerced to the DATETIME type by adding the time portion as '00:00:00'. To mimic the old behavior, use the CAST()
function to cause the comparison operands to be treated as previously.
For example:
You can use date_format()
mysql> select
TIMEDIFF(date_format('2014-01-26','%Y-%m-%d %H:%i:%s'), '2014-01-25 17:19:07')
as diff;
+----------+
| diff |
+----------+
| 06:40:53 |
+----------+
1 row in set (0.00 sec)
mysql> select date_format('2014-01-26','%Y-%m-%d %H:%i:%s') as date;
+---------------------+
| date |
+---------------------+
| 2014-01-26 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
how to change default date format when creating table in MYSQL
You can't change the default format for a date during the table definition stage. (It must always obey the DATETIME, DATE or TIMESTAMP formats.) As the manual puts it:
Although MySQL tries to interpret
values in several formats, dates
always must be given in year-month-day
order (for example, '98-09-04'),
rather than in the month-day-year or
day-month-year orders commonly used
elsewhere (for example, '09-04-98',
'04-09-98').
See the date and time reference docs for more info.
As such, you'll have to use the DATE_FORMAT() function at the point of output to achieve this goal.
You may want to use the STR_TO_DATE() and DATE_FORMAT() functions to communicate with MySQL using different date formats.
Example using STR_TO_DATE():
SELECT STR_TO_DATE('15-Dec-09 1:00:00 PM', '%d-%b-%y %h:%i:%S %p') AS date;
+---------------------+
| date |
+---------------------+
| 2009-12-15 13:00:00 |
+---------------------+
1 row in set (0.07 sec)
Example using DATE_FORMAT():
SELECT DATE_FORMAT('2009-12-15 13:00:00', '%d-%b-%y %h:%i:%S %p') AS date;
+-----------------------+
| date |
+-----------------------+
| 15-Dec-09 01:00:00 PM |
+-----------------------+
1 row in set (0.00 sec)