Mysql Function to find total no of seconds between two dates - mysql

Say i've a from date as 17/10/2012 and to date as 18/10/2012.How will i find total no of seconds that is available ?
Update I do not want to select a row which has exceed to date ?
Thanks in advance!

Here is the working demo.
http://sqlfiddle.com/#!2/d41d8/2869
SELECT UNIX_TIMESTAMP('2012-10-19') - UNIX_TIMESTAMP('2012-10-18') as differece_seconds;
"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."
You can simply use it with date coulmn.
Please check : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

Assuming your columns are proper DATE/DATETIME columns and not the date strings in your question, subtract the values of UNIX_TIMESTAMP()
SELECT UNIX_TIMESTAMP(date1_column) - UNIX_TIMESTAMP(date2_column) AS difference_seconds
If you have stored dates in the string format you posted above (which is a bad idea), you will need STR_TO_DATE() to first parse them into proper MySQL dates.
SELECT UNIX_TIMSTAMP(STR_TO_DATE('17/10/2012','%d/%m/%%Y')) - UNIX_TIMSTAMP(STR_TO_DATE('18/10/2012','%d/%m/%%Y')) AS difference_seconds

Use UNIX_TIMESTAMP() to get the seconds since epoch for a specific date. Then just subtract both values.
So assuming the values (in some DATE or DATETIME) are stored in col1 and col2 respectively, use can use something like this:
SELECT UNIX_TIMESTAMP( col1 ) - UNIX_TIMESTAMP( col2 ) AS diff FROM yourTable;

select timestampdiff(second,'2012-10-16','2012-10-18');
output will be
172800

Related

How to convert a date string to mysql date format for calculating date diff using mysql query

I have a column where a date store in ddmmyy format (e.g. 151216). How can I convert it to yyyy-mm-dd format (e.g 2016-12-15) for calculating a date difference from the current date? I try using DATE_FORMAT function but its not appropriate for this.
If you want to get the date difference, you can use to_days() after converting the string to a date using str_to_date():
select to_days(curdate()) - to_days(str_to_date(col, '%d%m%y'))
or datediff():
select datediff(curdate(), str_to_date(col, '%d%m%y'))
or timestampdiff():
select timestampdiff(day, str_to_date(col, '%d%m%y'), curdate())
You can use the function, STR_TO_DATE() for this.
STR_TO_DATE('151216', '%d%m%y')
A query would look something like:
select
foo.bar
from
foo
where
STR_TO_DATE(foo.baz, '%d%m%y') < CURDATE()
Note: Since both STR_TO_DATE() and CURDATE() return date objects, there's no reason to change the actual display format of the date. For this function, we just need to format it. If you wanted to display it in your query, you could use something like
DATE_FORMAT(STR_TO_DATE(foo.baz, '%d%m%y'), '%Y-%m-%d')
To get the difference, we can simply subtract time
select
to_days(CURDATE() - STR_TO_DATE(foo.baz, '%d%m%y')) as diff
from
foo
If you wanted to only select rows that have a difference of a specified amount, you can put the whole to_days(...) bit in your where clause.
SELECT STR_TO_DATE('151216', '%d%m%y') FROM `table`
use this '%d%m%y'

Only SELECT yesterdays date with weird date format

I need to only SELECT data where the date field is yesterdays date. The only problem I'm having is that the data in the date field looks like the following 20160412 062815.000
I don't really care about the time, I just want to search dynamically for anything with yesterdays date. I've tried a multitude of CURDATE() -1 but I'm unsure how to just search the first 8 digits of the field.
Assuming the date value is stored as a string, and the first 8 characters are always the date in YYYYMMDD format, then you can use a query like this:
select *
from your_table
where your_column like concat(date_format(current_date() - interval 1 day,'%Y%m%d'),'%')
One advantage of this query is that it can leverage an index on your date field, unlike the other answers so far.
Format yesterday's date to a number and convert the date string also to a number.
select * from your_table
where date_format(curdate() - interval 1 day, '%Y%m%d') * 1 = date_col * 1
SQLFiddle demo
*1 is a math operation that forces MySQL to convert strings to a number.
you can use subdate(currentDate, 1)
select * from your_table
where subdate(currentDate, 1) = DATE(your_date)

Read data stored as text and use in IF statement

I have a column that stores dates as text, I need to select all the entries with date less than the date of today.
If I use this:
SELECT *
FROM mytab
WHERE expire < CURRENT_DATE( )
ORDER BY expire DESC
It doesn't select the correct entries but only the ones with da_expire empty.
How can I fix it?
In the first place, why are you storing it as string?
You need to convert it to date using MySQL's builtin function so you can be able to compare it with today's date.
WHERE STR_TO_DATE(expire, '%Y/%m/%d %H:%i') < CURDATE()
This will be a little slower since it will not use any index if you have one defined on the column.
MySQL Docs: STR_TO_DATE()
Use STR_TO_DATE(expire, '%m/%d/%Y') instead of expire in the query. I have assumed you are storing the date in month day year format. You will need to adjust the format as per the string format. However, for performance reasons convert the type of expire during load/insert process .

How to combine date and time from different MySQL columns to compare to a full DateTime?

Column d is DATE, column t is time, column v is, for example, INT. Let's say I need all the values recorded after 15:00 of 01 Feb 2012 and on. If I write
SELECT * FROM `mytable` WHERE `d` > '2012-02-01' AND `t` > '15:00'
all the records made before 15:00 at any date are going to be excluded from the result set (as well as all made at 2012-02-01) while I want to see them. It seems it would be easy if there were a single DATETIME column, but there are separate columns for date and time instead in the case of mine.
The best I can see now is something like
SELECT * FROM `mytable` WHERE `d` >= '2012-02-02' OR (`d` = '2012-02-01' AND `t` > '15:00')
Any better ideas? Maybe there is a function for this in MySQL? Isn't there something like
SELECT * FROM `mytable` WHERE DateTime(`d`, `t`) > '2012-02-01 15:00'
possible?
You can use the mysql CONCAT() function to add the two columns together into one, and then compare them like this:
SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00'
The TIMESTAMP(expr1,expr2) function is explicitly for combining date and time values:
With a single argument, this function returns the date or datetime
expression expr as a datetime value. With two arguments, it adds the
time expression expr2 to the date or datetime expression expr1 and
returns the result as a datetime value.
This resulting usage is just what you predicted:
SELECT * FROM `mytable` WHERE TIMESTAMP(`d`, `t`) > '2012-02-01 15:00'
Here's a clean version that doesn't require string operations or conversion to to UTC timestamps across time zones.
DATE_ADD(date, INTERVAL time HOUR_SECOND)
All you have to do is to convert it into unix timestamp and make appropriate selections. For this you have to use mysql functions like *unix_timestamp().* and *date_format*
Suppose you want to select rows where timestamp > 1328725800, the following sql statement would do the task.
select unix_timestamp(d)+3600*date_format(t,'%h)+60*date_format(t,'%i')+date_format(t,'%S') as timestamp from table where timestamp>1328725800
Actually it should be:
SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00:00'
If you want to take seconds into account, you need to add the two digits to the end ;)

MYSQL - datetime to seconds

I wasn't able to find out (googling, reading mysql reference manual) how to get value of DATETIME in seconds in MySQL.
I dont mean to extract seconds from datetime, but to convert it into seconds.
If by "convert to seconds", you mean "convert to an UNIX Timestamp" (i.e. number of seconds since 1970-01-01), then you can use the UNIX_TIMESTAMP function :
select UNIX_TIMESTAMP(your_datetime_field)
from your_table
where ...
And, for the sake of completness, to convert from an Unix Timestamp to a datetime, you can use the FROM_UNIXTIME function.
If you want to have the difference between two DATETIME values, use TIMESTAMPDIFF:
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885
unit can also be HOUR which is what you asked for in one of the comments.
The unit argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
The level of usefulness of some of the other options will of course be determined by the granularity of the data. For instance, "MICROSECOND" will only have limited use if you are not storing microseconds in your DATETIME values.
Use TIME_TO_SEC in previous versions for mysql
SELECT TIME_TO_SEC(time column) FROM table
i used in mysql
TO_SECONDS(your date goes here) method to convert date to seconds from year 0
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
The function UNIX_TIMESTAMP(datetime) returns the unix time, which happens to be the number of seconds since 1-Jan-1970 0000 UTC. That may be what you need, but not if you're dealing with dates of birth, historical dates, or dates after 2037.
Starting in mysql 5.5.0 you can use to_seconds()
TO_SECONDS(FIELD_NAME)
FIELD_NAME must be DATETIME type
I have created my own query for your problem:
SELECT HOUR(`colname`) * 3600 + MINUTE(`colname`) * 60 + SECOND(`colname`)
FROM widgets
WHERE id = 1;
Use id = 1 if you have to take a specific row.
The output will be in seconds.