I have two unix timestamps 65 seconds apart and i am trying to query mysql in this manner
This is 65 seconds apart 1504684252 + 65
SELECT ask FROM live_rates WHERE the_time BETWEEN
UNIX_TIMESTAMP(1504684252) AND UNIX_TIMESTAMP(1504684317)
SELECT ask FROM live_rates WHERE the_time BETWEEN
FROM_UNIXTIME(1504684252) AND FROM_UNIXTIME(1504684317)
In my table, there is an event starting at timestamp 1504684252 and ending 65 seconds later. Why is there no data returned by either of the queries?.
Your question doesn't really make it clear what data type the_time is - if it's a unix timestamp (i.e. an integer) already, just query it as an integer, given that you seem to know the unix timestamps of your date range:
SELECT ask FROM live_rates WHERE the_time BETWEEN 1504684252 AND 1504684317
If your data in the_time is stored as a datetime, I'd say you should make sure that the server really is converting the values you've supplied to a datetime range that includes the relevant record:
SELECT ask FROM live_rates WHERE id = abcdef
SELECT FROM_UNIXTIME(1504684252), FROM_UNIXTIME(1504684317)
Run these two queries (with the id replaced) and eyeball the data. You'll find the reason, I'm sure - possibly something like a timezone issue, and your unix timestamps are translating to some time in UTC whereas your table data is showing some other time and you've hence mis-translated the time shown into a unix time.. Or possibly that it's an end date that has some time component outside the range of the unix times you specified even though the date part of it is correct.
It's hard to say for sure without a complete, verifiable example (a create table statement with inserted test data and a select demonstrating the problem. Try sqlfiddle.com)
ps; Don't use UNIX_TIMESTAMP() in the way you wrote here; it's not intended to have a unix timestamp passed into it. You either pass it no arguments (in which case it gives you the current datetime of the server clock, as a unix timestamp) or you pass it some datetime (and it will return you the equivalent unix timestamp of that datetime)
If the_time is a unix timestamp as opposed to a date i.e. 1504684252 instead of 2017-09-01 00:00:00, then you don't need FROM_UNIXTIME, which converts a unix timestamp to a date:
SELECT ask FROM live_rates WHERE the_time BETWEEN 1504684252 AND 1504684317
UNIX_TIMESTAMP takes a date/time as parameter and returns an integer. When you're feeding it with an integer it returns 0 - so you're selecting between 0 and 0.
FROM_UNIXTIME takes an integer but it returns a date/time - so if the_time is an integer they're not compatible.
Related
I would like some confirmation on how NOW function works in MySQL
According to the docs and when runing the this query SELECT NOW() the mysql returns the current time (local time i guess?) in following format YYYY-MM-DD HH-MM-SS.
If this is the case, then how come this works when comparing NOW() to a column that includes a UTC ISO date and time?
For example this works fine:
SELECT * FROM table where deadline > NOW() # deadline column contains a utc ISO string
Is the query above reliable or did it just return the correct answer by luck?
in case this is NOT reliable, how would you do the comparison?
MySQL NOW()-function returns a datetime in the session timezone. MySQL has UTC_TIMESTAMP()-function which returns current UTC date and time, which will work better when you are compare it to an UTC date time.
Note that you should store datetimes as DATETIME, instead of char/varchar (assume this is what you meant by "UTC ISO date and time").
I have a table created in phpMyAdmin and it contains two fields: start_time and text_modified. It looks like this
so the start_time might be null.
When I'm filling the data in phpmyadmin I can choose the date and time that should be represented as this timestamp:
After doing so I expect to store a timestamp value in this field instead of date time. But when I do a query SELECT start_time from table I see there this:
So I assumed that it is just the php my admin that shows me automatically all dates as a date time value instead of timestamps. But now when I do a query: SELECT FROM_UNIXTIME(start_time) FROM table I'm getting those results:
and instead I want normal dates here. What is going wrong here?
In a timestamp you can insert datetime values, that are internally stored as integers (the seconds since 1970-01-01 as you probably know). When you select them, they are displayed as date and time.
So far so good.
When you have values like 0000-00-00 00:00:00 you probably inserted NULL values or invalid dates or dates out of range for the integer value. Using FROM_UNIXTIME() doesn't make sense here, since this function calculates a date and time value from an integer value. This integer value of the timestamp column is like I said only used internally. Therefore you get NULL values for valid dates and 1970-01-01 for invalid dates since those were presumably treated as 0 and 0 seconds since 1970-01-01 00:00:00 is, surprise, 1970-01-01 00:00:00.
I have a blog where users can comment. I insert the time at which they posted a comment using NOW() and then use date('j M Y', stored timestamp) to show the time at which they posted.
I want to know does NOW() return the locatime of the end user or the localtime at my server.
Is it better suited to use UNIX_TIMESTAMP than NOW() to calculate the localtime at which users posted a comment.
The function NOW() generates a formatted date-time string, determined by the time zone of your MySQL server.
However, it would be better to store times using UNIX_TIMESTAMP(), which is expressed in GMT. Doing so makes it easier to format it according to the country of a visitor (e.g. using JavaScript).
If you still want to use DATETIME columns, you can store times using UTC_TIMESTAMP() (it formats a date like NOW() but expresses it in UTC); it should more or less work the same in all other aspects.
MySQL UNIX_TIMESTAMP() returns a Unix timestamp in seconds since '1970-01-01 00:00:00' UTC as an unsigned integer if no arguments are passed with UNIT_TIMESTAMP().
When this function used with date argument, it returns the value of the argument as an unsigned integer in seconds since '1970-01-01 00:00:00' UTC.
Argument may be a DATE, DATETIME,TIMESTAMP or a number in YYYYMMDD or YYMMDD.
Note : Since UNIX_TIMESTAMP() works on current datetime, your output may vary from the output shown.
NOW() returns the current date and time.
SELECT NOW(), UNIX_TIMESTAMP(NOW());
+---------------------+-----------------------+
| NOW() | UNIX_TIMESTAMP(NOW()) |
+---------------------+-----------------------+
| 2011-10-03 10:22:37 | 1317666157 |
+---------------------+-----------------------+
Let's see what the manual has to say about NOW():
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'
or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is
used in a string or numeric context. The value is expressed in the
current time zone.
... and UNIX_TIMESTAMP():
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.
So, to begin with, they return different things: a proper date versus an integer.
You actually need to get three features:
Store all dates in the same format (either UTC or the server's time zone)
Obtain user's time zone
Display stored date in user's time zone
The Date and Time functions chapter offers a summary of available functions. If you want to store dates in UTC you'd go for UTC_TIMESTAMP(). If you want to use server's time zone you can use NOW(). And there's CONVERT_TZ() to make conversions.
MySQL, however, won't help you with point #2. You need to either ask the user or use JavaScript to read user's clock and send it to the server so you can guess (if you don't ask you'll always need to guess because there're normally several time zones that share the same time in a given instant).
I have a table with the following columns:
|start_date |TZ |
|Dec 2, 2012 |Eastern |
|Dec 2, 2012 |GMT |
Note 1: our server is in UTC time.
Note 2:The column start_date is a date field, not a timestamp field. Dec 2nd 2012 implicitly means "2012-12-02 00:00:00"
Note 3: The above table is actually multiple normalized tables, but for simplicity, I de-normalized it.
Note 4: I can put anything into the TZ table to make this easy.
I would like to select from my_table where start_date <= now()
However, this doesn't work because of timezone. If the current date/time is
Dec 1st Eastern at 9PM (which is Dec 2nd 1AM UTC), the above query will return both results,
but I really only want the 2nd one. This is further complicated by daylight savings.
Ideally, I would like a query that does the following:
select * from my_table where convert_to_utc_timestamp(start_date,tz) <= now()
The above method would convert start_date to a timestamp and then convert it to the right timezone.
How would I do this in SQL?
There are two functions you'll probably find useful.
The first is:
STR_TO_DATE(start_date,'%M %d,%Y')
That will get your string, in the specified format, converted to a MySQL DATE datatype.
If you have the mysql.time_zone_name et al. tables populated, you can use the function:
CONVERT_TZ()
(need to check that CONVERT_TZ takes a DATE and will return a DATETIME or TIMESTAMP, or include a time component in the string being converted to get a DATETIME, e.g.
STR_TO_DATE( CONCAT(start_date,' 00:00:00'),'%M %d,%Y %T')
Wrap that expression in the CONVERT_TZ() function, e.g.
CONVERT_TZ( datetime_expr ,'US/Eastern','GMT')
To make use of the values stored in your TZ column, those are going to need to match, or you need to come up with a way to match to, the values stored in the mysql.time_zone_name table.
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.