What is the most convenient way to generate datetime in SQL? - mysql

SQL beginner here !
What is the most convenient way to create datetime objects within an SQL function, especially generating a datetime object for a given day, month, and year?
Thanks !

Everything you want to know about MySQL datetime functions is right here. Well, probably most everything.

In MySQL
CAST('YYYY-MM-DDThh:mm:ss:uuuuuu' AS datetime)
where:
YYYY: Year
MM : Month
DD : Day
hh : Hour
mm : Minutes
ss : Seconds
uuuuuu : Microseconds
EDIT: I changed from mmm (miliseconds) to uuuuuu (microseconds) since MySQL suports 6 digits

Given a datetime column: INSERT INTO Table ('datetime_column') VALUES (CURDATE( ))
Given a timestamp: INSERT INTO Table ('timestamp_column') VALUES (CURTIME())
Using unix time: INSERT INTO Table ('timestamp_column') VALUES (UNIX_TIMESTAMP())

Related

Date and time conversion query in SQL

In my database table, there is a date column i.e. EXPECTED DATE which is in dd-mm-yyyy format, and the datatype of the column is text. Now, I want to convert the format to yyyy-mm-dd. But the date is not changing at all and also when I tried to get the timestamp for the expected date column . I am getting some errors. For date coming I have used this STR_TO_DATE. But the year is not coming like what I expect and the timestamp also.
For example:
select STR_TO_DATE ('30-11-2011', '%d,%m,%y') as date ;
returns a result as
2020-11-30
And for timestamp
select STR_TO_DATE ('2011,11,30 12,30,45', '%y,%m,%d, %H,%I,%S');
I am not getting errors.
Please help me get the correct answers for this problem.
For the first query you need to use the %Y. Remember that it is always better to use "Y" for the years when you are writing a query for year.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For the second one also, you can use '%Y' in the place of '%y'. For minutes, use '%i' not '%I'. For hours and minutes, you can use whatever you like.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
Refer to the below documentation for more clarification on SQL commands.
You need %Y (capital Y) for the 4 digit year, when using MySQL's STR_TO_DATE. Also, minutes is represented by %i, not %I, the latter which is hours on a 0 to 12 scale. So use:
SELECT STR_TO_DATE('30-11-2011', '%d-%m-%Y');
SELECT STR_TO_DATE('2011,11,30 12,30,45', '%Y,%m,%d %H,%i,%S');
For the first query you need to use the %Y'.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For minutes, use this one only '%i'.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");

Query to Convert Varchar HH:MM to Integer Minutes in MySQL

I am having a table in MySQL Server where there is a column name StateStartTime and StateEndTime Datatype Varchar(100). It basically stores Time as HH:MM Format. As per the requirement now i it to gives me Minutes count i.e. 01:00 gives me 60, 01:30 -> 90. Please help me to write the query for MySQL, so that will convert Varchar (HH:MM) into Minutes(integer).
This Topic have the same problem but I need a solution for MySql
SELECT LTRIM(DATEDIFF(MINUTE, 0, StateStartTime))
FROM Time
Giving me error #1582 - Incorrect parameter count in the call to native function 'DATEDIFF'
You can try using the function TIME_TO_SEC() and divide the result by 60.
Example:
select TIME_TO_SEC(StateEndTime)/60 from table;

Remove milliseconds in a datetime field

I converted a database from MS SQL to MySql using workbench. There is a table that has a column called ActivityDate (datetime(6)) . For some reason, when that column got converted it has a dot in the date like (2013-05-03 11:20:20.420000) .
I want to remove the .420000 or whatever number is after the dot. I tried doing SUBSTRING_INDEX(ActivityDate,'.',1) but that didn't work, the last digits would just be .000000
I also tried UPDATEalerts.activitylogSETActivityDate= date_format(ActivityDate, '%Y-%m-%d %H:%i') WHEREactivitylog.ActivityLogID= 5;
And same issue... I get .000000 at the end
How can I do this?
Simply change the data type of the column to exclude the fractional part.
ALTER TABLE alerts.activitylog MODIFY ActivityDate DATETIME;
The type datetime(6) means 6 digits after the decimal point.
See the MySQL date and time fractional support documentation for details.
If you just want to select the datetime without the ms (like I was when I found this question) then the below CAST does the job:
SELECT CAST(created_at AS DATETIME) AS created_at_without_ms

T-SQL Select data from multiple days between certain times

In my table I have minute data about daily temperature measurements. The table looks like:
DateTime timestamp, Float temperature
I would like to have the temperatures on different dates between a certain interval and then only show the temperature between 7am and 8pm.
I know how to get the data between dates:
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
How to I implement the time restriction (7am - 8pm) as well?
Thanks a lot!!
If you are on SQL Server 2008 or above, you can use TIME datatype
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
AND CONVERT(TIME,[timestamp]) BETWEEN '19:00:00' AND '20:00:00'
EDIT: Also it is recommended to use ISO (yyyymmdd) date format when using date as a string. i.e.
BETWEEN '20121110' and '20121117'
The DateTime and TimeStamp values should contain precision you need, so
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
AND RIGHT([timestamp], 12) BETWEEN '19:00:00.000' AND '20:00.00.000'
You may need to adjust how many characters you are evaluating in the RIGHT predicate depending on the precision in your database. But the idea is to take all the parts that constitute the hours, minutes, seconds and miliseconds and restrict that to just those between the hours you require.

How to convert a dateformat from SQL Server to MySQL

I've been searching the internet for almost 6 hours now for the fastest solution to my problem.
I've got a SQL Server database where some of the tables have a DATETIME format for columns, but the values in these columns are in the following format:
DD-MM-YYYY HH:MM
eg.
18-12-2012 00:00
From my research MySQL only accepts the following format for its DATETIME values:
YYYY-MM-DD HH:MM:SS
Now, I'm actually trying to make the conversion in the Scripts themselves, not the database.
basically I have over 250,000 records in multiple tables in SQL Server Script Format.
I've already changed all the syntax to MySQL except this part.
Any help or advice would be appreciated. URGENT.
thank you
This is the Table
CREATE TABLE Price(
AirlineCode char(2) NOT NULL
, FlightNumber varchar(6) NOT NULL
, ClassCode char(3) NOT NULL
, TicketCode char(1) NOT NULL
, StartDate DateTime NOT NULL
, EndDate DateTime NOT NULL
, Price decimal NOT NULL
, PriceLeg1 decimal NULL
, PriceLeg2 decimal NULL
, PRIMARY KEY (
AirlineCode,
FlightNumber,
ClassCode,
TicketCode,
StartDate
)
, FOREIGN KEY (AirlineCode) REFERENCES Airlines (AirlineCode)
, FOREIGN KEY (ClassCode) REFERENCES TicketClass (ClassCode)
, FOREIGN KEY (TicketCode) REFERENCES TicketType (TicketCode));
and this is a sample insertion:
INSERT INTO Price VALUES ( 'QF', 'QF67', 'ECO', 'E', '18-12-2012 00:00', '04-01-2013 00:00', 3427.82, 1636.14, 2045.20 );
You can use MySQL STR_TO_DATE() function to convert dates from a known format to a datetime value. Assuming that you have dates in dd-mm-yyyy hh:mm (all numbers 0 padded and hh:mm is a 24-hour time) you can use:
SELECT STR_TO_DATE('18-12-2012 00:00', '%d-%m-%Y %k:%i')
-- 2012-12-18 00:00:00
You can use this function in your insert queries like so:
INSERT INTO Price VALUES (
'QF',
'QF67',
'ECO',
'E',
STR_TO_DATE('18-12-2012 00:00', '%d-%m-%Y %k:%i'),
STR_TO_DATE('04-01-2013 00:00', '%d-%m-%Y %k:%i'),
3427.82,
1636.14,
2045.20
);
Edit
If editing your insert queries is not possible, you can let MySQL do all the conversion. Temporarily change the datatype of datetime columns to VARCHAR and import the data. Then add a temporary field e.g. StartDate_Temp DATETIME and run an update query:
UPDATE Price SET StartDate_Temp = STR_TO_DATE(StartDate, '%d-%m-%Y %k:%i')
Once you've verified that your data is OK, delete the temporary columns.
Edited answer:
Also, you may use RegEx in SQL Server Management Studio:
Find what: {[0-9][0-9]}\-{[0-9][0-9]}\-{[0-9][0-9][0-9][0-9]} {[0-9][0-9]}\:{[0-9][0-9]}
Replace with:\3-\2-\1
First of all I would like to say thank you to all for your efforts. This was the first question I've ever asked at StackOverflow.com and am really impressed by the level of support.
After a little bit more research, I remembered the good old toolkit of RegEx that I learnt last year. So I decided to put it in some good use.
in Notepad++ thanks to its Regex search capabilities, I managed to trace down every date value in my 250000 records and replace them with the required ones.
([0-9][0-9])-([0-9][0-9])-([0-9][0-9][0-9][0-9]) ([0-9][0-9]:[0-9][0-9])
this was the search I put through for the date format that I had, and then i swapped the year and the day values and added the seconds in there as well by having the following in the Replace with box:
\3-\2-\1 \4:00
Problem solved.