Convert date, time stamp to date - sql

I have the data in the following format in varchar form. There are 48 million rows in this format
'2015-09-18 00:00:00.000'
and want to convert it to the following format
'2015-09-18'
Can anyone help me with the code in Oracle

If your column has a timestamp type, you simply need to use to_char to format it properly:
with yourTable(yourDateColumn) as
(
select to_timestamp('2015-09-18 00:00:00.000', 'YYYY-MM-DD HH24:MI:SS.FF') from dual
)
select to_char(yourDateColumn, 'yyyy-mm-dd')
from yourTable
If your column is a string ( and storing dates in string fields is generally a very bad idea) with a fixed format, you simply need a substr:
with yourTable(yourStringColumn) as
(
select '2015-09-18 00:00:00.000' from dual
)
select substr(yourStringColumn, 1, 10)
from yourTable

Related

Convert ISO-8601 varchar (0000-00-00T00:00:00+00:00) to datetime in SQL

How can I convert 2019-07-01T00:00:00+05:30 to DateTime in SQL?
2019-07-01T00:00:00+05:30 is a varchar field. I need to convert this into DateTime to compare this to a date field.
suggest me a query to Convert (2019-07-01T00:00:00+05:30) into DateTime
Convert To date :
select cast('2019-07-01T00:00:00+05:30' as Date)
Convert To time:
select cast('2019-07-01T00:00:00+05:30' as Time)
Convert To datetime :
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
Try any of these..
select cast(convert(datetime2, '2019-07-01T10:00:30+05:30',0) as datetime)
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
One option would be to use a combination of CONVERT on the timestamp without the timezone component, then use TODATETIMEOFFSET with the timezone portion to get the final result:
WITH yourTable AS (
SELECT '2019-07-01T00:00:00+05:30' AS dt
)
SELECT
TODATETIMEOFFSET(CONVERT(datetime, LEFT(dt, 19), 126), RIGHT(dt, 6)) AS output
FROM yourTable;
This outputs:
01/07/2019 00:00:00 +05:30
Demo
Unfortunately, SQL Server truncates the time zone information when converting from datetimeoffset to dateordatetime`. But, you can calculate the offset and add it back in:
select dateadd(minute,
datediff(minute, convert(datetimeoffset, dt), convert(datetime, convert(datetimeoffset, dt))),
convert(datetime, convert(datetimeoffset, dt))
)
from (values ('2019-07-01T00:00:00+05:30')) v(dt);
For your particular timezone, the date at midnight matches the UTC date, so you are safe. I'm on the other side of the world, so this would be a more important consideration in the "western" world ("west" being west of UTC).
The following query will convert the given VARCHAR to DATETIME value:
DECLARE #DateVal AS VARCHAR (30) = '2019-07-01T00:00:00+05:30';
SELECT CAST(REPLACE(SUBSTRING(#DateVal, 0, CHARINDEX('+', #DateVal)), 'T', ' ') AS DATETIME);

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

string to date - hive SQL

I am running queries in a hive environment.
I have a column which has a timestamp but is set up a string in the tables. I tried the following : all of them return Null
SELECT
,To_date(activitydate)
Cast:
,cast(activitydate as timestamp)
This is the how the data is set up in the table:
Appreciate any inputs on how I can convert this :
05/12/2017 00:00:00
SELECT
cust_id
,to_date(activitydate) activity_date
,type type_of_contact
FROM repl_task
WHERE to_date(activitydate) BETWEEN '2014-01-01' AND '2017-01-01' ;
I am running out of memory if I run this :
SELECT
cust_id
,activitydate
,SUBSTR(activitydate,4,2) AS DT
,SUBSTR(activitydate,0,2) AS MONTH
,SUBSTR(activitydate,7,4) AS YEAR
,type
FROM task
WHERE activitydate >='01/01/2016 00:00:00'
unix_timestamp function converts given format to unix timestamp and from_unixtime function converts from unix timestamp to given format:
hive> select from_unixtime(unix_timestamp('01/01/2016 00:00:00','MM/dd/yyyy HH:m:ss'),'yyyy-MM-dd');
OK
2016-01-01
Time taken: 0.118 seconds, Fetched: 1 row(s)
Can you try using to_date() with the date portion of your timestamp in ISO format:
SELECT
cust_id,
TO_DATE(CONCAT(SUBSTR(activitydate, 7, 4), '-',
SUBSTR(activitydate, 0, 2), '-',
SUBSTR(activitydate, 4, 2))) activity_date
type type_of_contact
FROM repl_task
WHERE
TO_DATE(CONCAT(SUBSTR(activitydate, 7, 4), '-',
SUBSTR(activitydate, 0, 2), '-',
SUBSTR(activitydate, 4, 2)))
BETWEEN '2014-01-01' AND '2017-01-01';
If this runs, but is not very performant, then you should consider storing your timestamps in ISO format. Storing dates as text, or as text in a non standard format, carries a penalty with most databases.

How to convert dates from varchar to datetime2 in SQL Server?

How can I convert these kind of date values from varchar to datetime2?
WITH dates AS (
SELECT '6.7.2012' AS dtm
UNION
SELECT '13.2.2012' AS dtm
UNION
SELECT '3.12.2012' AS dtm
UNION
SELECT '20.11.2012' AS dtm
)
SELECT CAST(dtm as datetime2) FROM dates
;
This results in an error:
Msg 241, Level 16, State 1, Line 6
Conversion failed when converting date and/or time from character string.
Use try_convert instead of cast:
WITH dates AS (
SELECT '6.7.2012' AS dtm
UNION
SELECT '13.2.2012' AS dtm
UNION
SELECT '3.12.2012' AS dtm
UNION
SELECT '20.11.2012' AS dtm
)
SELECT TRY_CONVERT(datetime2, dtm, 104) FROM dates
;
Results:
13.02.2012 00:00:00
20.11.2012 00:00:00
03.12.2012 00:00:00
06.07.2012 00:00:00
Note: try_convert was introduced in 2012 version, for earlier versions you need to use convert, risking an exception if the varchar value can't be converted using the specified style.

Use part of VARCHAR column as date in where clause

I have a table where the varchar column CREATED_BY has the data in the format
USER - dd/MM/yyyy hh:mm.
I'm trying to do data migration and need to get records where the created date is greater than a certain date, but the format of the column makes this difficult, so
SELECT * FROM TABLE_NAME WHERE -- last part of CREATED_BY > SOMEDATE
Well, since the dd/MM/yyyy hh:mm format has a fixed length, you can use the RIGHT function to extract the data part from your string:
SELECT *
FROM TABLE_NAME
WHERE CONVERT(datetime, RIGHT(CREATED_BY, 16), 103) > somedate
You need to extract the date from the string:
WHERE cast(reverse ( substring ( reverse ( #string ) , 1 , 16 ) ) as datetime) > somedate