I have data in the format of both "2013-01-17 18:46:47 -0800" and "1358477089" ...I'm wondering what is the best way to store this in a mysql db, that allows me to select results within a certain month, week, day etc.. using mysql's own functions.
Currently my create table code is like this.. the "timestamp" needs changing.
visible
CREATE TABLE IF NOT EXISTS `votes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`from` varchar(32) NOT NULL,
`username` varchar(32) NOT NULL,
`address` varchar(16) NOT NULL,
`timestamp` varchar(32) NOT NULL,
PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Best way is to use MySQL built-in DATETIME type.
MySQL offers lots of function which will allow you to select results within a certain month, week, day, whatever you need.
See great list of functions here:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
As hek2mgl and other guys mentioned, there is also TIMESTAMP.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored.
I preffer and advice you to use DATETIME.
If you use a timestamp your field should be an "integer" not a varchar. This provides better perfomance (for example if you use an index for this column).
If you do not need to have dates before 1970 I would suggest to use a timestamp, not a datetime. It is easier to use.
PHP
$timestamp = date('U');
MySQL
INSERT INTO table SET timestamp = UNIX_TIMESTAMP()
Related
I want to set the default value in a TIME column in a MySQL DB table to be '08:00:00' regardless of timezone. I can't quite figure out the syntax.
create table venues (venue_id SERIAL PRIMARY KEY, name VARCHAR(100), address VARCHAR(250), open_time TIME DEFAULT '08:00:00'::TIME, close_time TIME DEFAULT '20:00:00'::TIME, activities VARCHAR(250);
It has a problem with how i'm trying to set the default values for the two TIME columns. I also tried using '08:00:00'::time without time zone
'08:00:00'::TIME is how you do a type cast in Postgres, not MySQL. MySQL uses the SQL standard cast. Similarly time without time zone is a Postgres type.
You don't need a type cast at all, MySQL (and Postgres) will cast it to the column type.
create table venues (
venue_id SERIAL PRIMARY KEY,
name VARCHAR(100),
address VARCHAR(250),
open_time TIME DEFAULT '08:00:00',
close_time TIME DEFAULT '20:00:00',
activities VARCHAR(250)
);
dbfiddle
::TIME casts are not needed for the TIME columns
I have to develop a application using MySQL and I have to save values like "1412792828893" which represent a timestamp but with a precision of a millisecond. That is, the amount of milliseconds since 1.1.1970. I declare the row as timestamp but unfortunately this didn't work. All values are set to 0000-00-00 00:00:00
CREATE TABLE IF NOT EXISTS `probability` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`segment_id` int(11) NOT NULL,
`probability` float NOT NULL,
`measured_at` timestamp NOT NULL,
`provider_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ;
How should be the declaration in order to be able to save timestamp values with this precision?
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.
For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');
please create the table like this by mentioning the length (length can be whatever digit count that you want by milliseconds) of timestamp timestamp(2) or timestamp(3) or timestamp(5) likewise. the Mysql version should be 5.6 or above.
https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
CREATE TABLE IF NOT EXISTS `probability` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`measured_at` timestamp(2) NOT NULL,
PRIMARY KEY (`id`)
) ;
and then pass the timestamp through Java.
statement.setTimestamp(2, new Timestamp(new Date().getTime()))
You can use BIGINT as follows:
CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
);
I am trying to create a table in MySQL that has a timestamp field that is 7 days ahead of now() is there a way to do this?
This is my current code
CREATE TABLE tbl_reg
(
reg_id int(7) NOT NULL auto_increment KEY,
user_id int(7) NOT NULL,
registration_key char(50) NOT NULL,
registration_expires timestamp default now()+7days,
stamp_created timestamp default now()
);
Can anyone help as i cant find anything like this on the mysql site and wondered if there was a way to do it?
There are a number of date/time functions in MySQL that will do the trick here.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
registration_expires=DATE_ADD(NOW(), INTERVAL 7 DAY)
You can't set an expression as a default, though - you'll need to do it in your INSERT queries. Notice that even if your expr value is > 1 there is no plural used for the unit value.
Or you could create a view from a query where you add the interval, or when you query the db always add the 7 days interval.
I have a large table of birthdays that I want to convert from a varchar column to a date column.
The table SQL is:
CREATE TABLE `birthdays` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`uid` bigint(20) DEFAULT NULL,
`birthday_date` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
The birthday date is stored in one of two ways: strings like "05/26/1994" or sometimes "03/14" (for people who don't want to reveal their birth year).
What is the best way to create another table and store the birthdays in a date column? Is it possible to do this just using MySQL (and avoid using PHP or some other intermediary)?
I have found a STR_TO_DATE function in MySQL. Should I use this?
Thanks!
SELECT IF(birthday_date RLIKE '[0-9]{2}/[0-9]{2}/[0-9]{4}',STR_TO_DATE(birthday_date,'%m/%d/%Y'),STR_TO_DATE(birthday_date,'%m/%d'));
This will result in dates like 0000-03-14 for rows that have no year entered. Your server needs to be configured to allow invalid dates though (see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html )
If you convert your column to DateTime then you will not be able to store dates like "03/14" in which year is missing. So instead I suggest to keep this as it is and probably have another column for storing the dateTime if you really need that.
Also have internal trigger to convert the datestrings from varchar column to dateTime column.
yes, you have to use the method STR_TO_DATE for your purpose.
There are some other questions where people have problems with timestamp being all zeros. I have checked them and this is not a duplicate.
I declare a table like this:
CREATE TABLE `my_db`.`my_table` (
`time_stamp` timestamp NOT NULL,
`author` varchar() NOT NULL,
`text` text NOT NULL,
`md5` int(11) NOT NULL,
PRIMARY KEY (`time_stamp`)
) ;
I also have a second table which will have a timestamp as primary key and they should have the same value.
Coding in Delphi, I use SELECT CURRENT_TIMESTAMP which returns something like '19/6/2010 4:56:17 AM' which I then use in an INSERT statement. The INSERT succeeds, but the timestamp is all zeros.
What am I doing wrong?
Here's the INSERT code:
sqlCommand := 'INSERT INTO my_db.my_table(time_stamp, author, text, md5) VALUES ("'
+ timestamp +
'", "mawg", ' +
'"Hello, world"' +
0 +
'");';
Result := DoSQlCommandWithNoResultSet(sqlCommand, AdoConnection);
Insertion will be extremely low rate, one entry every few weeks or maybe months, so I am happy with timestamp as primary key. I am keeping "versions" of things, so timestamp makes sense to me.
I am begging to think that this is an ADO problem, although I would expect ADO to just "pass through". I don't see any other solution. In a console, the output is "correct", but when run through ADO in Delphi then it is wrong
Can I specify to MySQL how it ought to format its dates?
After reviewing the MySQL documentation, it appears that if your timestamp value is incorrectly formatted, it would normally cause the timestamp to be '0000-00-00 00:00:00'.
In any case, you don't need to specify a timestamp value—that's the benefit of TIMESTAMP over DATETIME. And even if you did, you can simply set it to NOW() instead of running an unnecessary SELECT statement.
Edit:
Also, I know you said you thought this through, but have you considered daylight savings time? This could cause two records to have the same timestamp when the clock is set back during autumn.
Edit 2:
K, I don't know why I didn't catch this earlier, but that timestamp format you gave is incorrect. Try inserting a valid timestamp like '2010/06/19 4:56:17'. MySQL has pretty relaxed parsing of date & time values, but it always has to be year-month-date and hour-minute-seconds.
Edit 3:
Alright, there seems to be a little confusion over this, so I'm gonna post this quote from the MySQL 5.0 doc page on the DATETIME format:
For values specified as strings that include date part delimiters, it is not necessary to specify two digits for month or day values that are less than 10. '1979-6-9' is the same as '1979-06-09'. Similarly, for values specified as strings that include time part delimiters, it is not necessary to specify two digits for hour, minute, or second values that are less than 10. '1979-10-30 1:2:3' is the same as '1979-10-30 01:02:03'.
Have a look at MySQL date functions. They are very extensive and allow a high flexibility.
Besides all that, I would recommend re-thinking your table structure. A timestap as a primary key is not exactly what you want. When you have high traffic, it CAN happen, that the timestamp is the same. Also if you are saving 2 or more records in a row, the timestamp will be the same. Furthermore, your MD5 column is set to int(11). MD5 hashes use mixed characters, so i would rather go with varchar(32).
CREATE TABLE `my_db`.`my_table` (
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL,
`author` varchar(100) NOT NULL,
`text` text NOT NULL,
`md5` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ;
AFAIR 19/6/2010 4:56:17 AM is not a valid date format for MySQL date types. You should convert it to 2010-06-19 04:56:14 (see doc).