With the string DATETIME yyyymmddhhmmss like 20160125173013, I would like to convert this string into hh:mm:ss (17:30:13) as a new column called "Time" in a table with sql update statement. However I am only able to convert it into 17:30 using the stuff function.
Is there any possible solution to convert?
In my statement
UPDATE db
SET Time =convert(time, stuff(substring(DATETIME,9,6),3,2,':'))
FROM db
WHERE Time IS NULL
Real Output=17:13:00.0000000
But my expected output is 17:13:00
Thanks a lot!
Here is the miracle for mysql:
SELECT time(str_to_date('20160125173013', '%Y%m%d%H%i%s'));
Do you have an actual DATETIME field? If so you can use DATE_FORMAT():
UPDATE mytable SET my_time=DATE_FORMAT(my_date, '%H:%i:%s')
If you don't have a native DATETIME field I hope you can convert it to one, as irregular, quirky formats cause trouble and introduce a lot of overhead when parsing to convert. STR_TO_DATE() can do the opposite of DATE_FORMAT() and convert from arbitrary strings to native DATE or DATETIME values.
Don't confuse STORAGE with PRESENTATION
Declare #YourTable table (DateTime varchar(25),Time time)
Insert Into #YourTable values
('20160125173013',null)
Update #YourTable
Set Time = stuff(left(right(DateTime,6),4),3,0,':')
Select *
,FormatedTime = Format(cast(Time as datetime),'HH:mm')
From #YourTable
Returns
DateTime Time FormatedTime
20160125173013 17:30:00.0000000 17:30
Based on the use of the STUFF function I believe this is Microsoft SQL Server, and not MySql.
Therefor, you can do something like this:
UPDATE db
SET [Time] = CAST(SUBSTRING([DATETIME], 9, 2) +':'+
SUBSTRING([DATETIME], 11, 2) +':'+
RIGHT([DATETIME], 2) As Time)
WHERE [Time] IS NULL
Your string is no format, SQL Server will cast implicitly
DECLARE #YourDateTimeString VARCHAR(100)='20160125173013';
The following query will cut the first 8 digits and cast them to DATE, which works implicitly (unseparated format). The time is cut from the right side, then the two :-signs are stuffed into the right places:
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME);
The result
2016-01-25 17:30:13.0000000
If you need this as string without the trailing .0000000 (which is a pure output format question and should be done in your presentation layer!) you can just use LEFT(). The input of this function is string (again implicitly casted), the output is a text which looks like a time.
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,LEFT(CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME),8);
The result
2016-01-25 17:30:13
If you ar eusing SQL server then use Convert function
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
--Declare
set #VarCharDate = '20160125173013' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' +
SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2)
+ ' ' + SUBSTRING(#VarCharDate,9,2)
+':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
select Convert(varchar(8),convert(datetime, #VarCharDate1, 120),114)
Related
How can a ISO datetime String timestamp be correctly parsed to time type column in mysql? I noticed the following:
select CAST('2013-09-05T10:10:02' as time) from mytable limit 1
Result incorrect:
00:20:13
select CAST(CAST('2013-09-05T10:10:02' as datetime) as time) from mytable limit 1
Result correct:
10:10:02
Why do I have to make a double CAST here to get the correct time? And more important: how is time parsing done property?
Because you have a string which you need to first cast it into date format.
If you cast it in time like below:
select CAST('2014-09-05T10:10:02' as time)
00:20:14
select CAST('2015-09-05T10:10:02' as time)
00:20:15
select CAST('2013' as time) --below casting string as time
00:20:13
If you monitor closely its treating it as string and getting year as time.
So you need to cast it datetime first then time.
select CAST(CAST('2013-09-05T10:10:02' as datetime) as time)
Basically when you try to convert something to a time that looks like an integer MySQL treats that as something in the form HHMMSS, so your 2013-09-05T10:10:02 becomes 00:20:13. To convert properly, the value needs to be a MySQL datetime, which you can do via CAST or you can use STR_TO_DATE to convert your date string to a MySQL date, then TIME to extract the time part of it:
SELECT TIME(STR_TO_DATE('2013-09-05T10:10:02', '%Y-%m-%dT%H:%i:%s'))
Output:
10:10:02
Demo on dbfiddle
I want to concatenate Date And Date Name Together. How Can I do it.
I need output like
2015-10-09 Friday
I got the DateName= `SELECT DATENAME(dw,'2015-10-09') as MyDateName`
Is it possible to make it in a single query?
Try this:
select CAST('2015-10-09' as varchar(10)) + ' ' +DATENAME(dw,'2015-10-09')
SQLFIDDLE DEMO
If your date is already in the varchar format then you dont need to CAST the date and simply try to concatenate them using +
select '2015-10-09' + ' ' +DATENAME(dw,'2015-10-09')
Since the value you provided is already a string, and DATENAME also returns a string, you can just concatenate together with +:
SELECT '2015-10-09 ' + DATENAME(WEEKDAY,'2015-10-09') as MyDateName
Assuming that in reality this is a parameter or a column of datatype datetime, you'll need to convert it to varchar first. There is no built in style for converting to varchar which contains the Day name, so you'll have to do the work yourself in two parts.
See MSDN page on cast and convert for the built in formats.
For the sake of my example, I'll create a datetime variable to use for tests:
DECLARE #d DATETIME; SET #d = '20151009';
Then to convert it to VARCHAR:
For the date part, ODBC is closest to the format you've asked for with the format yyyy-mm-dd hh:mi:ss(24h). So to get the date in that format as a varchar, you can use CONVERT with that style, value, 20.
SELECT CONVERT(VARCHAR(10), #d, 20)
Note I have converted it to VARCHAR(10) to truncate the timepart of the datetime that you don't want in the output. Then if you concatenate this with a space and the day name you already worked out, you can get your output:
SELECT CONVERT(VARCHAR(10), #d, 20) + ' ' + DATENAME(WEEKDAY, '2015-10-09') AS MyDateName
(Replace my variable with a column name and add a FROM statement if you're after output from a table)
You can try this code:
SELECT
CAST(CAST(GETDATE() AS DATE) AS VARCHAR) + ' ' + DATENAME(DW, GETDATE()) AS [DATE_WITH_WEEKNAME]
I'm curious what the right way is to construct a query where the rows are pulled based on a timestamp that represents a specific month. Given that different months have different numbers of days, is there a way to generate a query that always gives you the rows where the timestamp contains the current month so that the results would only include the current month?
Do you mean something like this
SELECT * FROM tbl WHERE
MONTH(timesp) = MONTH(NOW()) AND
YEAR(timesp) = YEAR(NOW());
You can use the FROM_UNIXTIME() function:
SELECT *
FROM tableName
WHERE MONTH(FROM_UNIXTIME(timestampField))==6
Just use MONTH:
select *
from foo
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
Try this sql.
select *
from yourtable
where yourdatefield>=DATE_SUB(CURDATE(),INTERVAL 1 MONTH);
You're looking for something like this:
SELECT * FROM table where MONTH(date_row) = $month;
If you have an index on your date field, then this is efficient (T-SQL syntax, the idea applieas to any RDBMS though)
SELECT
*
FROM
tableName
WHERE
dateTimeField
BETWEEN
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
AND
-- add one month, subtract one day
DATEADD(mm, 1,
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
) - 1
Of course any other method to get two datetime values in the right range would work.
SQL Server has LEFT(CONVERT(varchar, GETDATE(), 120), 8) + '01' to convert a datetime to string, other Db servers have their own functions to do the same. Maybe you can calculate the two values in the calling application more easily - how you get them, is not the point.
The point is that BETWEEN can use an index, whereas the other solutions that work with WHERE MONTH(dateTimeField) = 6 will trigger a table scan, which is about the slowest operation you can do on a table.
I know there is a function called ISDATE to validate DATETIME columns, but it works only for the SMALLDATETIME and DATETIME types.
Is there a similar way to validate the new data type DATETIME2 in SQL Server 2008 and 2012?
In SQL Server 2012, you can use TRY_CONVERT:
SELECT TRY_CONVERT(DATETIME2, '2012-02-02 13:42:55.2323623'),
TRY_CONVERT(DATETIME2, '2012-02-31 13:42:55.2323623');
Results:
2012-02-02 13:42:55.2323623 NULL
Or TRY_PARSE:
SELECT TRY_PARSE('2012-02-02 13:42:55.2323623' AS DATETIME2),
TRY_PARSE('2012-02-31 13:42:55.2323623' AS DATETIME2);
(Same results.)
Sorry that I don't have a clever answer for you for < SQL Server 2012. You could, I guess, say
SELECT ISDATE(LEFT('2012-02-02 13:42:55.2323623', 23));
But that feels dirty.
TRY_CONVERT documentation on Microsoft Docs
TRY_PARSE documentation on Microsoft Docs
Be careful using the LEFT(..., 23) solution on database systems using another dateformat than mdy (and SQL-Server 2008). You can see the dateformat of the current session using the DBCC USEROPTIONS command.
On a database system using the german dateformat (dmy) the LEFT(..., 23) solution isn't working (detected on dates with day > 12). See the following test case:
-- test table using a DATETIME and DATETIME2 column.
CREATE TABLE dt_vs_dt2 (
dt DATETIME,
dt2 DATETIME2
);
-- set a datetime values with a day > 12.
DECLARE #date_value AS DATETIME = DATEADD(DAY, 18 - DAY(GETDATE()), GETDATE());
-- insert the current date into both columns using GETDATE.
-- note: using the following on a day > 12
INSERT INTO dt_vs_dt2 VALUES (#date_value, #date_value);
-- let's have a look at the values.
-- the values look the same (the datetime2 is more precise as expected).
SELECT dt, dt2 FROM dt_vs_dt2;
-- now we expect both values are valid date values.
-- to validate the datetime2 value, the LEFT(..., 23) solution is used.
SELECT ISDATE(dt), ISDATE(LEFT(dt2, 23))
FROM dt_vs_dt2;
How to solve that?
You can use a CAST(column_name AS DATETIME) instead of the LEFT(..., 23) to make this work:
-- using a CAST(... AS DATETIME) instead of `LEFT(..., 23)` seems to work.
SELECT dt, CAST(dt2 AS DATETIME) AS dt2
FROM dt_vs_dt2;
-- now both values are valid dates.
SELECT ISDATE(dt) AS dt, ISDATE(CAST(dt2 AS DATETIME)) AS dt2
FROM dt_vs_dt2;
demo on dbfiddle.uk (using dmy) / demo on dbfiddle.uk (using mdy)
On SQL Server 2012 and later you should use the TRY_PARSE / TRY_CONVERT solution described in #Aaron Bertrand answer. The CAST(... AS DATETIME) solution explained in this answer should also work.
Not a very good title, so my apologies.
For some reason, (I wasn't the person who did it, i digress) we have a table structure where the field type for a date is varchar. (odd).
We have some dates, such as:
1932-04-01 00:00:00 and 1929-07-04 00:00:00
I need to do a query which will convert these date strings into a unix time stamp, however, in mySQL if you convert a date which is before 1970 it will return 0.
Any ideas?
Thanks so much!
EDIT: Wrong date format. ooops.
Aha! We've found a solution!
The SQL to do it:
SELECT DATEDIFF( STR_TO_DATE('04-07-1988','%d-%m-%Y'),FROM_UNIXTIME(0))*24*3600 -> 583977600
SELECT DATEDIFF( STR_TO_DATE('04-07-1968','%d-%m-%Y'),FROM_UNIXTIME(0))*24*3600 -> -47174400
This could be useful for future reference.
You can test it here: http://www.onlineconversion.com/unix_time.htm
I've adapted the DATEDIFF workaround to also include time not just days. I've wrapped it up into a stored function, but you can just extract the SELECT part out if you don't want to use functions.
DELIMITER |
CREATE FUNCTION SIGNED_UNIX_TIMESTAMP (d DATETIME)
RETURNS BIGINT
DETERMINISTIC
BEGIN
DECLARE tz VARCHAR(100);
DECLARE ts BIGINT;
SET tz = ##time_zone;
SET time_zone = '+00:00';
SELECT DATEDIFF(d, FROM_UNIXTIME(0)) * 86400 +
TIME_TO_SEC(
TIMEDIFF(
d,
DATE_ADD(MAKEDATE(YEAR(d), DAYOFYEAR(d)), INTERVAL 0 HOUR)
)
) INTO ts;
SET time_zone = tz;
return ts;
END|
DELIMITER ;
-- SELECT UNIX_TIMESTAMP('1900-01-02 03:45:00');
-- will return 0
-- SELECT SIGNED_UNIX_TIMESTAMP('1900-01-02 03:45:00');
-- will return -2208888900
convert these date strings into a
unix time stamp
Traditional Unix timestamps are an unsigned integer count of seconds since 1-Jan-1970 therefore can't represent any date before that.
At best you will have mixed results depending on the system you are using to represent the timestamp.
From wikipedia
There was originally some controversy
over whether the Unix time_t should
be signed or unsigned. If unsigned,
its range in the future would be
doubled, postponing the 32-bit
overflow (by 68 years). However, it
would then be incapable of
representing times prior to 1970.
Dennis Ritchie, when asked about this
issue, said that he hadn't thought
very deeply about it, but was of the
opinion that the ability to represent
all times within his lifetime would be
nice. (Ritchie's birth, in 1941, is
around Unix time −893 400 000.) The
consensus is for time_t to be signed,
and this is the usual practice. The
software development platform for
version 6 of the QNX operating system
has an unsigned 32-bit time_t, though
older releases used a signed type.
It appears that MySQL treats timestamps as an unsigned integer, meaning that times before the Epoc will all resolve to 0.
This being the case, you always have the option to implement your own unsigned timestamp type and use that for your calculations.
If its feasible for your problem, you could shift all your mysql times by, say 100 years, and then work with those adjusted timestamps or re calculate the negative timestamp value.
As some have said, make sure your system is using 64bits to represent the timestamp otherwise you'll hit the year 2038 problem.
I have not tried the above solutions but this might in case you are not able to retrieve the date value from the MySQL database in the form of timestamp, then this operation can also be tried
SELECT TIMESTAMPDIFF(second,FROM_UNIXTIME(0),'1960-01-01 00:00:00');
To get the max. Range +/- wise use this query on your birthday field, in my case "yyyy-mm-dd" but you can change it to your needs
select name, (#bday:=STR_TO_DATE(birthday,"%Y-%m-%d")),if(year(#bday)<1970,UNIX_TIMESTAMP(adddate(#bday, interval 68 year))-2145916800,UNIX_TIMESTAMP(#bday)) from people
I feel like we're making this much too difficult...
Use my functions below so you can convert anything to and from unix timestamps, much like you do in a browser.
Call functions like this:
select to_unix_time('1776-07-04 10:02:00'),
from_unix_time(-6106024680000);
By compiling these:
delimiter $$
create function to_unix_time (
p_datetime datetime
) returns bigint
deterministic
begin
declare v_ret bigint;
select round(timestampdiff(
microsecond,
'1970-01-01 00:00:00',
p_datetime
) / 1000, 0)
into v_ret;
return v_ret;
end$$
create function from_unix_time (
p_time bigint
) returns datetime(6)
deterministic
begin
declare v_ret datetime(6);
select '1970-01-01 00:00:00' +
interval (p_time * 1000) microsecond
into v_ret;
return v_ret;
end$$
Use Date instead of timestamps. Date will solve your Problems.
check this link