UNIX_TIMESTAMP outputting NULL in MySQL? - mysql

I've got a table setup which has populated data. In column "date", I have dates in the following format:
yyyymmdd i.e. 20131110
I have created a new field and called it newdate with the text format.
Then, I open up the SQL window and put the following in
UPDATE wl_daily
SET
newdate = UNIX_TIMESTAMP(date)
For some reason, it is running correctly, however it only outputs NULL to all the rows. Also, the column name is blank for some reason
Any suggestions?

That's because your field in a string and you're trying to add timestamp to it which is not a string. You need to use a valid datetime field like timestamp for this to work.
Advice: don't store dates and times as strings. Store them in their native format. It makes working with dates and times much easier.

While John Cronde's answer is correct - it doesnt help your situtation
UNIX_TIMESTAMP(STR_TO_DATE(`date`, '%Y%m%d'))
will do the conversion for example
SELECT UNIX_TIMESTAMP(STR_TO_DATE('20131111', '%Y%m%d'))
returns
unix_timestamp(STR_TO_DATE('20131111', '%Y%m%d'))
---------------------------------------------------
1384128000
You should only use this to convert your columns to the date specific columns. Converting each time you need a number will add load and slow down the query if used in production

Related

How can I convert a varchar into a date in MySQL Workbench?

Probably it's super simple but i've been stuck some hours on this.
I have a column called "Publish_Date" which is a varchar, but my date shows like this: 17.01.11 (year.day.month) and I want to convert it to a date (at this point, any date format it's ok).
Every time i tried to use "convert" or "cast" it gives me a syntax error or the data doesn't change or all the data in the column changes to "null" values.
I'd appreciate if you can help me.
Assuming your data is all greater than 2000 then you can add missing part of YEAR then cast it.
SELECT CAST(CONCAT('20', Publish_Date) AS DATETIME);
You can use STR_TO_DATE with the format %y.%m.%d since this is how your date value is stored
select
str_to_date(birth_date, '%y.%m.%d')
from
mytable
Here is an SQL Fiddle I created for this case

Snowflake interpreting timestamp wrong?

I'm loading a bunch of semi-structured data (JSON) into my database through Snowflake. The timestamp values in the entries are javascript timestamps that look like this:
"time": 1621447619899
Snowflake automatically converts this into a timestamp variable that looks like this:
53351-08-15 22:04:10.000.
All good so far. However, I think that the new timestamp is wrong. The actual datetime should by May 19, 2021 around 12pm MDT. Am I reading it wrong? Is it dependent on the timezone that my Snowflake instance is in?
When comparing the following options manually in SQL:
with x as (
SELECT parse_json('{time:1621447619899}') as var
)
SELECT var:time,
var:time::number,
var:time::varchar::timestamp,
1621447619899::timestamp,
'1621447619899'::timestamp,
var:time::timestamp
FROM x;
It appears that what you want to do is execute the following:
var:time::varchar::timestamp
Reviewing the documentation it does look like the to_timestamp is looking for the number as a string, so you need to cast to varchar first, and then cast to timestamp, otherwise you get what you are getting.
The question says that Snowflake transforms it to "53351-08-15 22:04:10.000" looks right, but it doesn't look right to me.
When I try the input number in Snowflake I get this:
select '1621447619899'::timestamp;
-- 2021-05-19T18:06:59.899Z
That makes a lot more sense.
You'll need to provide more code or context for further debugging - but if you tell Snowflake to transform that number to a timestamp, you'll get the correct timestamp out.
See the rules that Snowflake uses here:
https://docs.snowflake.com/en/sql-reference/functions/to_timestamp.html#usage-notes
The ::timestamp handles strings and numeric inputs differently. I.e. a string is added to 1970-01-01 as milliseconds (correct) whereas the numeric value is added in seconds which returns a date way in the future "53351-08-18 20:38:19.000".
SELECT TO_VARCHAR(1621447619899::timestamp) AS numeric_input
,'1621447619899'::timestamp AS string_input
numeric_input = 53351-08-18 20:38:19.000
string_input = 2021-05-19 18:06:59.899
Solutions are to convert to a string or divide by 1000:
SELECT TO_TIMESTAMP(time::string)
SELECT TO_TIMESTAMP(time/1000)

How to convert a string to date and extract values in Access query

I'm using Access DB 2007 - 2010; I've tried to import many CSV files but the timestamp column keeps failing to import correctly.
So I linked all of the CSV's to an Access DB and I'm trying to query all of the tables.
I'm trying to extract the year and day of the year from the time stamp (which is currently a string)
I'm trying to combine the Format with datepart functions and it keeps failing. (it just says error in the table)
The format function by itself works but I can't combine it with anything.
I'm basically trying to do this:
select datepart("y", Format(gmt, "dd-mmm-yyyy hh:nn:ss")) as DOY from Table1;
but it fails. I've also tried CDate and DateValue in different combinations but it all fails.
Does anyone know how to get this to work?
UPDATE
The format function isn't doing anything. The text remains the same no matter how I try to format it.
Here's a datetime sample: 05-Dec-2008 13:40:01.955
Access can't cope with the milliseconds in your date strings.
Use Left() to exclude them and feed the resulting substring to CDate().
SELECT CDate(Left(gmt, 20)) AS date_from_string
FROM Table1;
Once you have a valid Date/Time value, you can use Year(<Date/Time value>) or DatePart("yyyy", <Date/Time value>) to extract the year. And DatePart("y", <Date/Time value>) will give you the day of the year.
Just solve this issue, here is my code for your reference:
update tablename
set date=cdate(format(left(gmt,4)&"-"&right(gmt,2),"yyyy-mm"))

Update-Set for a Date type not processing query part correctly in MS Access 2007

I'm trying to extract a text date into a date type field and change the format from yyyymmdd to ddmmyyyy in the process. I have set up a simple select statement checking that the dates are valid and if not setting a default date and this worked fine, no bad dates.
SELECT
IIf(isdate(Format(Left([EffectiveDate],10),"dd/mm/yyyy")),Format(Left([EffectiveDate],10),"dd/mm/yyyy"),#01/01/1900#) AS Expr1
FROM Relationships;
But when I embed this exact same select statement in an Update Set Query:
UPDATE Relationships
SET MSDate = IIf(isdate(Format(Left([EffectiveDate],10),"dd/mm/yyyy")),Format(Left([EffectiveDate],10),"dd/mm/yyyy"),#01/01/1900#);
the dates are formed as mmddyyyy and not ddmmyyyy as the select query does.
Interestingly, when I tried to change the format type to "long date"
UPDATE Relationships
SET MSDate = IIf(isdate(Format(Left([EffectiveDate],10),"long date")),Format(Left([EffectiveDate],10),"dd/mm/yyyy"),#01/01/1900#);
I got the default 01/01/1900 result suggesting what was extracted was not a valid date. By the way, just using the query in a Select statement worked just fine.
I can't help thinking that something is happening in the conversion to date type. I even tried to do DateValue on the query but still no joy.
Since you're using Left([EffectiveDate],10), I assume that the text field actually contains yyyy-mm-dd (the ISO format).
You should leave the string in this format (Access understands ISO and US format mm/dd/yyyy best), and convert it with the CDate() function.
UPDATE Relationships
SET MSDate = IIf(IsDate(Left([EffectiveDate],10)),
CDate(Left([EffectiveDate],10)),
#1900-01-01#);

Error when using DateAdd - TSQL

I have an app that uses a table that has a varchar column [BadColumn] which is populated by a date in the format MM/DD/YYYY or at least that's what most of the rows contain.
I have no control on modifying this table and changing the data type.
I need to report on this data to show rows that are within a week.
Here's my problem:
every time I use something to compare/filter the date I get an error
Conversion failed when converting date and/or time from character string
So here's what I have tried so far :
Tried to create a view with the [BadColumn] being converted to a Date type column [NewBadColumn] and convert the value from the original table to a date type using Convert(date, BadColumn). The view gets populated, but now when I still try to query using DateADD or do any date comparisons I get the same error.
I have also tried to use Convert(Date, BadColumn, 105), but same problem.
I have tried other formats, but still the same issue cannot do a date comparison on that column.
I am not sure which row is throwing the error, how do I find it and fix this issue.
Thank you for the responses. I have tried using ISDate function to find the bad records.
But I am still getting the same error "Conversion failed when converting date and/or time from character string." when I try to use DateAdd.
Here's the code I am using :
Select t.*
from
(Select * from dbo.BadTableName q with (nolock)
where ISDate(BadColumn)=1 and ISDATE(BadColumn) Is Not Null
) t
where t.BadColumn > DATEADD(dd,-2, GetDATE())
Any help is appreciated.
Try checking the column using the ISDATE() function. You can do this without creating a view first.
IF ISDATE(YourColumn) = 1
DATEADD (datepart , number , YourColumn )
ELSE 'No valid date provided'
Look at this other stack over flow question and answer
Find invalid dates in SQL Server 2008
You can use the ISDATE function to test the individual rows.