How to convert DATETIME to TIMESTAMP in mysql? - mysql

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.

Related

What happens if you add an integer to a datetime in mysql?

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.

Mysql - date and time columns to datetime

I have been trying to merge date and time into datetime. My date is varchar and I need to have got one column datetime (as datetime)
My input is like that:
create table t1 (
date1 varchar (12),
time1 varchar (39));
INSERT INTO t1 VALUES
('01.Mar.2019', '11:30'),
('02.Mar.2019', '1:30'),
('03.Mar.2019', '0:30'),
('03.Mar.2019', '10:30');
And the desired results are below:
datetime1
01.Mar.2019 11:30:00
02.Mar.2019 01:30:00
03.Mar.2019 00:30:00
03.Mar.2019 10:30:00
SELECT STR_TO_DATE(CONCAT(date1,' ',time1),'%d.%b.%Y %H:%i') x FROM t1;
+---------------------+
| x |
+---------------------+
| 2019-03-01 11:30:00 |
| 2019-03-02 01:30:00 |
| 2019-03-03 00:30:00 |
| 2019-03-03 10:30:00 |
+---------------------+
4 rows in set (0.00 sec)
Although I feel that the way you are storing these values is not the best solution, you can present the data in its current stored format as a DATETIME by using CONCAT to join the separate VARCHARs together and then STR_TO_DATE to convert the string into a DATETIME:
SELECT STR_TO_DATE(CONCAT(date1, ' ', time1), '%d.%b.%Y %k:%i') FROM t1;
This is broken into two parts:
CONCAT(date1, ' ', time1)
Joins the date and time together with a space into a single string that will look like this:
01.Mar.2019 11:30
02.Mar.2019 1:30
03.Mar.2019 0:30
03.Mar.2019 10:30
Then, STR_TO_DATE converts this to a DATETIME using format specifiers:
STR_TO_DATE(CONCAT(date1, ' ', time1), '%d.%b.%Y %k:%i')
So, the formats are:
%d - Day of the month with leading zero if it is 1 number (01, 02, 03, and so on)
%b - Three-characters abbreviated month name (Jan, Feb, Mar, and so on)
%Y - Four digits year (2018, 2019, and so on)
%k - Hour in 24-hour format without leading zero (0, 1, 2, and so on)
%i - Minutes with leading zero (00, 01, 02, and so on)
The output from this will be:
2019-03-01 11:30:00
2019-03-02 01:30:00
2019-03-03 00:30:00
2019-03-03 10:30:00
I just want to add that I feel that the best way to store date and time information in the database is almost certainly to use a DATETIME column.

mysql getting epoch time

I am using a table with:
CREATE TABLE tv (
datetime datetime NOT NULL,
value int(4),
metric varchar(25),
PRIMARY KEY (datetime)
);
My system is in CET so I get this from a select:
select * from tv;
+---------------------+-------+----------+
| datetime | value | metric |
+---------------------+-------+----------+
| 2017-08-09 14:17:27 | 0 | TV power |
| 2017-08-09 14:20:04 | 0 | TV power |
| 2017-08-09 14:40:04 | 0 | TV power |
| 2017-08-09 14:45:03 | 0 | TV power |
When I try to graph it (in grafana), I use:
SELECT
UNIX_TIMESTAMP(datetime) as time_sec,
value,
metric
FROM tv
ORDER BY datetime
And it works fine except that it writes everything with 2 hours more in the future. So I guess this is because the UNIX_TIMESTAMP is thinking that the datetime is in UTC and looking at the system value, as it is CET, it is doing a +02:00 before converting to epoch or something like this.
I get this also:
SELECT ##global.time_zone;
+--------------------+
| ##global.time_zone |
+--------------------+
| SYSTEM |
+--------------------+
1 row in set (0.00 sec)
Meaning it is using the system timezone which is CET.
How can I get my UNIX_TIMESTAMP to convert correctly to the CET?
Thanks.
Here is what the documentation has to say about UNIX_TIMESTAMP:
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.
From what I understand, MySQL is shifting the input timestamp to UTC time, doing the calculation, and then returning the offset still in UTC time. One option to correct for this would be to shift your timestamps from "UTC" time to "CET" time before calling UNIX_TIMESTAMP. I use quotes here, because your timestamps are already in the desired CET timezone, but we have to spoof MySQL by countering its own efforts to be smart and convert everything to UTC.
Something along these lines should work:
SELECT
UNIX_TIMESTAMP(CONVERT_TZ(datetime, 'UTC', 'CET')) AS time_sec,
value,
metric
FROM tv
ORDER BY datetime
Once again, we are shifting your timestamps from UTC to CET time, to offset UNIX_TIMESTAMP() which will be doing the opposite of that.
If the call above to CONVERT_TZ() does not work for you, you may have to spend some time configuring your MySQL timezone tables. Here is a SO question which will get you started:
Database returned an invalid value in QuerySet.dates()
As a final comment, I think the best long term solution for you would be to just store your timestamps in UTC time. Then, you only need to convert for incoming and outgoing dates, but not for internal MySQL calculations. Storing all timestamp information in UTC time is a common database practice.

MySQL convert YYYY-MM-DD to unix timestamp

I want to convert a YYYY-MM-DD column to unix timestamp. Similar to this question: MySQL - Convert MM/DD/YY to Unix timestamp
MySQL does not seem to transform a value of '2012-05-10' to the correct unixtime. Here is the suggested function that fails:
SELECT UNIX_TIMESTAMP(CAST(dateid AS DATE)) AS unixtime
What version of MySQL you are using? As tested by MySQL 5.5.27 in SQLFiddle these two queries worked
SELECT UNIX_TIMESTAMP(CAST('2012-05-10 00:00:00' AS DATETIME)) As UnixTime;
SELECT UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) As UnixTime;
SQLFiddle Demo
I'm not sure what the problem you are having exactly, but the following works fine:
CREATE TABLE ex (dt VARCHAR(20));
INSERT INTO ex SET dt = '2012-05-10';
SELECT
UNIX_TIMESTAMP('2012-05-10') ex1,
UNIX_TIMESTAMP(dt) ex2,
UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) ex3,
UNIX_TIMESTAMP(CAST(dt AS DATE)) ex4
FROM ex;
returns:
+------------+------------+------------+------------+
| ex1 | ex2 | ex3 | ex4 |
+------------+------------+------------+------------+
| 1336633200 | 1336633200 | 1336633200 | 1336633200 |
+------------+------------+------------+------------+
As you can see, there is no need to CAST() if the string is in the form YYYY-MM-DD or YYYY-MM-DD HH:MM:SS, as MySQL implicitly converts strings in this format to DATEs.
See http://sqlfiddle.com/#!2/1a215/3

How to convert human date to unix timestamp in Mysql?

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