MySQL STR_TO_DATE Problem while using this function - mysql

As title, I'm trying to convert a VARCHAR column in a DATE column, and data is populated in that format "DDMMYYYY" ex. XMAS is "25122022" and in this case the correct formula should be STR_TO_DATE(column, '%d%m%Y')Well, when I execute this query I get an error since in some cases I have values with a "missing" char, I mean, for example, "1012023" when the day is <10 the query fails, cause it checks for "01122023" instead.I could solve this easily by adding a 0 to all fields having length 7, but I'd like to make it more clean.Reading better the usage of STR_TO_DATE I noticed that I could replace %d with %e since the second choice should theorically consider days from 0 to 31 instead of 01 to 31.Unexpectedly the query didn't work and gave me the same erorr at the first instance of a length 7 string.Am I doing something wrong?Thanks in advance.

We can try left padding your date string with zero to a length of 8:
WITH yourTable AS (
SELECT '1012023' AS dt
)
SELECT STR_TO_DATE(LPAD(dt, 8, '0'), '%d%m%Y') AS dt_out -- 2023-01-01
FROM yourTable;
Demo

Related

MySQL TIMESTAMPDIFF returns 0 even though there is 1 hour difference between two values

I feel like I am doing something wrong but I cannot understand what.
Let's say I have a query:
select timestampdiff(minute, '2022-10-31t11:25:00.000', '2022-10-31t12:25:00.000')
It returns 0 but it should return 60, no? There is a 1 hour difference between the two. It returns anything other than 0 only if the date is different. What is wrong here?
Your query is not using valid MySQL timestamp literals. If you want a T separator between the date and time portions of the timestamps, it must be uppercase. From the MySQL documentation:
The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.
SELECT TIMESTAMPDIFF(minute,
'2022-10-31T11:25:00.000',
'2022-10-31T12:25:00.000'); -- 60

Date and time conversion query in SQL

In my database table, there is a date column i.e. EXPECTED DATE which is in dd-mm-yyyy format, and the datatype of the column is text. Now, I want to convert the format to yyyy-mm-dd. But the date is not changing at all and also when I tried to get the timestamp for the expected date column . I am getting some errors. For date coming I have used this STR_TO_DATE. But the year is not coming like what I expect and the timestamp also.
For example:
select STR_TO_DATE ('30-11-2011', '%d,%m,%y') as date ;
returns a result as
2020-11-30
And for timestamp
select STR_TO_DATE ('2011,11,30 12,30,45', '%y,%m,%d, %H,%I,%S');
I am not getting errors.
Please help me get the correct answers for this problem.
For the first query you need to use the %Y. Remember that it is always better to use "Y" for the years when you are writing a query for year.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For the second one also, you can use '%Y' in the place of '%y'. For minutes, use '%i' not '%I'. For hours and minutes, you can use whatever you like.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
Refer to the below documentation for more clarification on SQL commands.
You need %Y (capital Y) for the 4 digit year, when using MySQL's STR_TO_DATE. Also, minutes is represented by %i, not %I, the latter which is hours on a 0 to 12 scale. So use:
SELECT STR_TO_DATE('30-11-2011', '%d-%m-%Y');
SELECT STR_TO_DATE('2011,11,30 12,30,45', '%Y,%m,%d %H,%i,%S');
For the first query you need to use the %Y'.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For minutes, use this one only '%i'.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");

Difference between two dates in MySQL with DATE() function

I am using DATE() function to calculate the difference between two dates in MySQL
value of SYSDATE() function is following
select SYSDATE();
2020-07-15 12:16:07.0
When I am using date from same month, it is giving correct result
select DATE(SYSDATE())- DATE('2020-07-13');
2
But when I am using date from last month it is giving difference as 86 instead of 16;
select DATE(SYSDATE())- DATE('2020-06-29');
86
Edit:
I am aware that we can use DATEDIFF() but I want to verify why DATE() function is giving results like this since we are already using this in code
MySQL doesn't support subtracting one date from another. The code
SELECT DATE '2020-07-15' - DATE '2020-06-29';
should hence result in an error, but MySQL silently converts this to this instead:
SELECT 20200715 - 20200629;
Seeing that you want to subtract two values, it assumes that you want to work with numbers. Dates are not numbers, but their internal representation yyyymmdd can be represented numerically. So, while CAST(DATE '2020-07-15 ' AS int) fails with a syntax error, as it should, MySQL is not consistent, when it comes to subtraction. It generates the numbers 20200715 and 20200629 and works with these.
I consider this a bug. MySQL should either raise an exception or return an INTERVAL when subtracting one DATE from another.

Mysql text to data format especially to MM:SS

I am wondering how to express average time formatted like "MM:SS". I have a table typed with text.
myTable1
09:37
10:17
...
If I changed myTable to TIME type, which returns "hour:minute:00", not "MM:SS"
myTable2
09:37:00
10:17:00
So, what I found is
avg(time_format(sec_to_time(round(time_to_sec(TPP)/60, 0)), '%i:%s'))
It returns
myTable3
09:37
10:17
my final goal is averaging those rows
When I use avg() on myTable1,3 it returns '9.5000'
as I expected it returns '09:57'
My questions came from the goal to average myTable1 to be with "MM:SS" formatted
How about adding the hour component and not dividing by 60?
time_format(sec_to_time(avg(time_to_sec(concat('00:', TPP)
)
)
), '%i:%s'
)
The avg() should also be called on the numeric value of seconds, before the conversion back to a time format.
You want to first convert your string to time, then seconds, in order to compute the average. Then convert back to a string with the desired format :
TIME_FORMAT(SEC_TO_TIME(
AVG(TIME_TO_SEC(STR_TO_DATE(TPP, '%h:%i')))
), '%h:%i')

Casting negative integer to DATE in SQL

I'm having a problem working with a Navicat Database. I got a column in SQL called fechaNacimiento (Birthdate) that should be a Date type, but instead it's stored as integers (most negative integers):
SELECT fechaNacimiento FROM Registrados
And I'm getting:
fechaNacimiento
-1451678400
-2082829392
-1798746192
-1199221200
-1356984000
-694299600
-1483214400
-1924976592
-1830368592
-2019670992
-1678909392
239252400
1451617200
-879541200
I don't know how this dates where loaded, I just know that inside that negative integer there's a date, and nobody here have any clue about how to spell SQL, so I have nobodoy to ask. If I just cast it to DATETIME, I get all of them as NULL values. Any idea in how to convert this data to Date type?
Numbers like that make me think of Unix times, number of seconds since 1970. If so, you might be able to do:
select dateadd(second, <column>, '1970-01-01')
This would put the negative values sometime before 1970 (for instance, -1678909392 is 1916-10-19). If you have older dates, then that might be the format being used.
These might also be represented as milliseconds. If so:
select dateadd(second, <column>/1000, '1970-01-01')
In this case, -1678909392 represents 1969-12-12.
In MySQL, you would use:
select '1970-01-01' + interval floor(column / 1000) second