SQLite Parsing TEXT column with date info - sql

I'am using SQLite DB and I have "Date" column that is VARCHAR
I need to extract data between 2 dates...
this is what I tried....
SELECT * FROM Table1 WHERE Date BETWEEN '14/03/2017 17:00:10' AND '16/03/2018 17:00:12'
SELECT * FROM Table1 WHERE strftime('%d/%m/%y %H:%M:%S', Date) BETWEEN strftime('%d/%m/%y %H:%M:%S','15/07/2016 20:00:09') AND strftime('%d/%m/%y %H:%M:%S','16/07/2017 21:00:09')
SELECT * FROM Table1 WHERE strftime('%d/%m/%y %H:%M:%S', Date) BETWEEN '2017/07/15 20:00:09' AND '2017/07/17 21:00:09'
Any idea what I am doing wrong ?

If you have a date/time column, then just do:
SELECT t1.*
FROM Table1 t1
WHERE t1.Date >= '2017-03-14 17:00:10' AND
t1.Date < '2018-03-16 17:00:12';
Use ISO/ANSI standard date formats for constants!
I strongly discourage you from using between with date/time values. Here is a blog post on the subject, which although for SQL Server applies to all databases.

You can't use SQLite's strftime because it's formatting function, it can not parse input string.
Basically you have two options:
try to parse string using builtin functions
create user defined function
If you can rely on the fixed positions, you can easily parse your string and format it back to comply with one of supported SQLite DateTime formats. In your case it might look like this:
SELECT [Date] FROM Table1 WHERE
DATETIME(printf('%04d-%02d-%02d %02d:%02d:%02d',
substr([Date], 7, 4), substr([Date], 4, 2), substr([Date], 1, 2),
substr([Date], 12, 2), substr([Date], 15, 2), substr([Date], 18, 2)))
BETWEEN '2017-07-15 20:00:05' AND '2017-07-17 21:00:09'
Please note you have to change also syntax of BETWEEN to match one of supported DATETIME formats.

Related

convert date in string format to date datatype sql

I have values in a column named Date as a nvarachar data type in the form of mmddyy and want to convert the values to a date datatype in the form of yyyy-mm-dd, what sql colde can I use to convert the value.
example
02121955 -> 1955-02-12
You can use datefromparts():
select datefromparts(right(str, 4), left(str, 2), substring(str, 3, 2))
Or reconstruct it as yyyymmdd format and just convert:
select convert(date, left(right(str, 4) + str, 8))
Here is a db<>fiddle.
I have found a similar Question to yours that has been solved: https://stackoverflow.com/a/39139155/14940878
Here is the Code changed for your requests:
declare #date varchar(max)='02121955'
select convert(varchar(8),cast(CONCAT(SUBSTRING(#date,5,4),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,3,2)) as date),112)as [YYYYMMDD]
You need to take each field and concat it into one and then convert it to datetime.
SUBSTRING(#date,5,4) - Takes the last four characters.
SUBSTRING(#date,1,2) - Takes the first two.
SUBSTRING(#date,3,2) - Takes the two in the middle.
Assuming it's SQL Server, I think you just need
select cast(format(02121955,'##-##-####') as date)
DEMO

Invalid datetime string when CAST As Date

I have Time column in BigQuery, the values of which look like this: 2020-09-01-07:53:19 it is a STRING format. I need to extract just the date. Desired output: 2020-09-01.
My query:
SELECT
CAST(a.Time AS date) as Date
from `table_a`
The error message is: Invalid datetime string "2020-09-02-02:17:49"
You could also use the parse_datetime(), then convert to a date.
with temp as (select '2020-09-02-02:17:49' as Time)
select
date(parse_datetime('%Y-%m-%d-%T',Time)) as new_date
from temp
How about just taking the left-most 10 characters?
select substr(a.time, 1, 10)
If you want this as a date, then:
select parse_date('%Y-%m-%d', substr(a.time, 1, 10))
select STR_TO_DATE('2020-09-08 00:58:09','%Y-%m-%d') from DUAL;
or to be more specific as your column do as:
select STR_TO_DATE(a.Time,'%Y-%m-%d') from `table_a`;
Note: this format is applicable where mysql is supported

Error when converting varchar to date ddmmyyyy

I have a varchar column with the following format ddmmyyyy and I'm trying to convert it to date in the format dd-mm-yyyy. I'm using the query below but I get the error:
Conversion failed when converting date and/or time from character string.
select *, coalesce(try_convert(date, newdate, 105), convert(date, newdate))
from mydate
You don't have a date, you have a string. So, you can use string operations:
select stuff(stuff(newdate, 5, 0, '-'), 3, 0, '-')
If you want to convert to a date, you can do:
select convert(date, concat(right(newdate, 4), substring(newdate, 3, 2), left(newdate, 2)))
You could then format this as you want.
However, you should not be converting the value to a date. You should be storing it as a date in the first place.
To turn your string to a date, you can just [try_]cast() it; SQL Server is usually flexible enough to figure out the format by itself:
try_cast(newdate as date)
If you want to turn it back to a string in the target format, then you can use format():
format(try_cast(newdate as date), 'dd-MM-yyyy')
Compared to pure string operations, the upside of the try_cast()/format() approach is that it validates that the string is a valid date in the process.
Have to agree with the others. Why are you storing a date as a string in the first place? In a non-standard format, no less? Here's one way, but you should really fix the data model. Store dates as dates.
DECLARE #badIdea table (dt char(8));
INSERT #badIdea(dt) VALUES('21052020');
SELECT newdate = TRY_CONVERT(date, RIGHT(dt,4) + SUBSTRING(dt,3,2) + LEFT(dt,2))
FROM #badIdea;
BTW 105 won't work because it requires dashes. This works:
SELECT CONVERT(date, '21-05-2020', 105);
That's a bad format too, IMHO, because who knows if 07-08-2020 is July 8th or August 7th. But at least that one is supported by SQL Server. Your current choice is not.
SQL doesn't store date data types in different formats, and it's probably not a good idea to try and adjust this.
If, however, you are wanting a result set to simply display the date in a different format, you are on the right track. You just need to convert your date data type to a string.
SELECT *
, COALESCE ( TRY_CONVERT ( CHAR(10), newdate, 105 ), CONVERT ( CHAR(10), newdate ) )
FROM mydate

How to convert timestamp to date in SQL?

Image: http://i.stack.imgur.com/CyyHo.jpg
I have a dataset as shown in the image. I want to use the values of created_date column as datetime format. How can i do that?
The time you would like to convert is called Unix timestamp, which means how many seconds have passed since 1970/01/01. In this occasion you will have to use DATA function, which will take the total number of seconds and add them to 1970/01/01.
In SQL it is done in the following way:
select DATEADD(s, dateTimeInSeconds, '19700101')
Where s is Seconds and dateTimeInSeconds is your value of date; '19700101' is a starting point.
Column values does not seems to be a TimeStamp.
Use the below script to make the values as datetime .
SELECT credits,amount,city,
CONVERT(DATETIME,LEFT(created_date,8)
+' '+SUBSTRING(created_date,9,2)
+':'+SUBSTRING(created_date,11,2)
+':'+RIGHT(created_date,2)) Created_Date
FROM YourTable
Is created_date of type 'epoch'? And are you trying to use the datetime format within the SQL database or within your business logic? If it is in the business logic, it then depends on the language you use. I'd love to help but I don't fully understand the use case. If you could provide more information that would help us help you!
Cheers!
It doesn't look like unix timestamp but datetime without some chars (just digits are left).
To get "real" timestamp use in MySql: unix_timestamp()
To convert "real" timestamp to datetime use in MySql: FROM_UNIXTIME()
To convert your column to datetime use:
CONCAT(SUBSTR(created_date, 1, 4),
'-',
SUBSTR(created_date, 5, 2),
'-',
SUBSTR(created_date, 6, 2),
' ',
SUBSTR(created_date, 7, 2),
':',
SUBSTR(created_date, 11, 2),
':',
SUBSTR(created_date, 13, 2))

query to search dates which are stored as string in the database

I have a table where I store an activity completion date as varchar. The format of the date stored is MM/DD/YYYY HH:MM:SS.
I have search window where I have two fields Completion date from and completion date to.The date format selected here is MM/DD/YYYY.
How do I write a query such that I am able to fetch the activity completion between two given dates from the table which has the dates stores as varchar.This table was created a long time back and no thought was given to saving dates as datetime.
You can use SQL CONVERT to change your columns to DATE format but that will cause performance issues.
SELECT *
FROM MyTable
WHERE CONVERT(DATETIME, MyDate) >= CONVERT(DATE, '01/01/2014')
AND CONVERT(DATETIME, MyDate) <= CONVERT(DATE, '01/31/2014')
CONVERT documentation - http://msdn.microsoft.com/en-us/library/ms187928.aspx
if you are unable to change how data is stored, than for better performance , you can create view with calculated column that converts VARCHAR to DATETIME. After that can create index on calculated column. Index on Computed Column documentation
Use the SUBSTRING function to get the date parts in a comparable order (i.e. yyyymmdd):
select *
from mytable
where
CONCAT( SUBSTRING(thedate, 7, 4) , SUBSTRING(thedate, 4, 2) , SUBSTRING(thedate, 1, 2) )
between
CONCAT( SUBSTRING(#FROMDATE, 7, 4) , SUBSTRING(#FROMDATE, 4, 2) , SUBSTRING(#FROMDATE, 1, 2) )
and
CONCAT( SUBSTRING(#TODATE, 7, 4) , SUBSTRING(#TODATE, 4, 2) , SUBSTRING(#TODATE, 1, 2) )
;
You could use this code :
select * from table_name
where CAST(col1 as date )
between CAST(Completion date from as date )
and CAST(Completion date to as date);
Function syntax CAST:
CAST ( expression AS data_type )
You can use below if the date format is {yyyy-MM-dd}, or you can adjust the charindex's index value depending on format
SELECT *
FROM table
WHERE
CHARINDEX('-', col_value, 0) = 5
AND CHARINDEX('-', col_value, 6) = 8
AND LEN(col_value) = 10
The above piece will look for first occurrence of char '-' at position 5 and the second char '-' at position 8 while the entire date value's length is equal to 10 chars
This is not full proof, but will narrow down the search. If you want to add time then just expand the criteria in the where to accommodate the format i.e. {yyyy-MM-dd 00:00:00.000}
This is a safe way to query the data, without any unexpected 'invalid cast / convert' errors.