SQL Convert String to Date - sql

I am trying to find a way of extracting the first part of line of string and separating as a date. The following is an example of some of the data.
17/10/12 lskell Still waiting for one more signature on the
I have tried casting the whole field as a date, and converting to a date, but these fail?
Would anyone have any ideas?

Try this for MySql
DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(columnname,' ',1), '%d/%m/%y'), '%Y-%m-%d')

If you know that
the first "word" in your string will always be a date
the date will always be separated from the rest of the string by a space
the date will have a consistent format
you are working in MySQL
then try this:
SELECT CAST(SUBSTRING_INDEX(myfield, ' ', 1) AS DATE) adate FROM mytable;

Try:
SELECT SUBSTRING('10/17/12 lskell Still waiting for one more signature on the', 1, 8)

(assuming date comes in this format)
-- MYSQL:
SELECT Str_to_Date(Left(yourstring,8),'%d/%m/%y') from yourtable;
-- Oracle
SELECT TO_DATE(left(yourstring,8),'dd/mm/yy')
from your table;
--- sql server
SELECT CONVERT(DATETIME,left(yourstring,8),120) from your table;

Related

Issue with splitting string in bigquery

I cant seem to split this string, I would like to get the last 8 numbers as 'Date' in the format of YYYY-MM-DD. I would like to use the _filename to feed through and generate the date.
select
split(split("gs://mmmm_ssss_count_detail/mmm_ssss_count_detail_20220125.csv",'/')[offset(2)],'_')[offset(3)]
This just gives me 'detail' which is not what I need, it should at least give me '20220125.csv' where I can then remove the .csv part and parsedate it to 'Date' in my main select query.
Help please.
Instead of a split, can you use a regex to find the date value? If so try the following:
select
parse_date("%Y%m%d",regexp_extract(path, r'_(\d+)\.csv'))
from sample_data
The regex string above is looking for a pattern where a set of digits (\d+) exists between an _ and .csv
With the sample string you provided it yields:
Consider below approach / option
select _filename,
parse_date('%Y%m%d', array_reverse(split(replace(_filename, '.', '_'), '_'))[offset(1)]) file_date
from your_table
if applied to sample data in your question - output is

Trying to convert SQL getdate into varchar with no in-between characters

I have a list of auto-generated tables in MS-SQLServer that differ only in the date listed at the end of the name.
The challenge is that I want to create a script that always references a table 'x days back'.
So for example if the table name would be:
dbo.tablename_20200825
I can get "close" to the date format I need as a string with the following statement and style
select convert(varchar(10), getdate(), 102);
However I still have those periods of separation between each part of the date.
How do I make the resulting string appear as '20200825' instead of '2020.08.25'
Thank you as always for any insight and help.
I think you're looking for 112
select convert(varchar(10), getdate(), 112);
Results
20200825
You can use format() to get exactly what you want:
select format(getdate(), 'yyyyMMdd')

Convert Number type to Date in postgres SQL

I have a numeric data in a column 20170930, need help in converting it into Date in PostgreSQL , tried multiple ways but non seems to work
You can convert to a string and then to a date:
select column::text::date
You can also express this using explicit cast() syntax:
select cast(cast(20170930 as text) as date)
Use one of the following :
SELECT cast(yourcol::varchar as date ) as dt1, yourcol::varchar::date as dt2
where dt1 and dt2 values of type date, and yourcol is a numeric value such as 20170930
Demo
The best thing is to change column datatype into Date type,
ALTER TABLE table_name
ADD column_name Date;
As shown above, PostgreSQL supports a full set of SQL date and time types, as shown in the table below. Dates are counted according to the Gregorian calendar. Here, all the types have a resolution of 1 microsecond / 14 digits except date type, whose resolution is day.
Please try below query
SELECT to_date(column::varchar,'YYYYMMDD')
For anybody who fell into my pitfall I tried this but my numeric was like a 'seconds past 01-01-1970 format' rather than YYYYMMDD
This worked
SELECT to_timestamp(yourcol) as numeric_column_now_date
from yourtable
see here
https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT

"Conversion failed when converting" Is there a way to det. what row/ entry?

Is there a way to determine what row/ date entry SQL is having trouble converting ? There are 300k date entries and I'm unsure which one my code is having a problem with. This code has worked in the past.
Conversion failed when converting date and/or time from character
string
You could use TRY_CONVERT to search for invalid date literals:
SELECT *
FROM tab_name
WHERE TRY_CONVERT(DATE, col_name) IS NULL
AND col_name IS NOT NULL;
If necessary you could provide date time style.
db<>fiddle demo
You can check if the column was in a date format, using ISDATE():
select myColumnDate
from myTable
where ISDATE(myColumnDate) = 0

SQL query to convert Date to another format

Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.
The Column is paid_month and the values are below.
200901
200902
So,please help in writing SQL query to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .
Thanks
Rohit
Hi,
I am sorry for missing in giving the whole information.
1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902
3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.
4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy
I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.
**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**
It looks like YYYYMM - depending on your database variant, try STR_TO_DATE(paid_month, 'YYYYMM'), then format that.
Note: MM/DD/YYYY is not "normal" format - only Americans use it. The rest of the world uses DD/MM/YYYY
For MySQL check
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
Example:
SELECT DATE_FORMAT(NOW(), '%d/%m/%Y')
For MySQL, you would use the STR_TO_DATE function, see http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE(paid_month,'%Y%m');
Sounds like the column contains some normal dates and some YYYYMM dates. If the goal is to update the entire column, you can attempt to isolate the YYYYMM dates and update only those. Something like:
UPDATE YourTable
SET paid_month = DATE_FORMAT(STR_TO_DATE(paid_month, '%Y%m'), '%m/%d/%Y')
WHERE LENGTH(paid_month) = 6
SELECT (paid_month % 100) + "/01/" + (paid_month/100) AS paid_day
FROM tbl;
I'm not sure about how oracle concatenates strings. Often, you see || in SQL:
SELECT foo || bar FROM ...
or functions:
SELECT cat (foo, bar) FROM ...