Mysql - date and time columns to datetime - mysql

I have been trying to merge date and time into datetime. My date is varchar and I need to have got one column datetime (as datetime)
My input is like that:
create table t1 (
date1 varchar (12),
time1 varchar (39));
INSERT INTO t1 VALUES
('01.Mar.2019', '11:30'),
('02.Mar.2019', '1:30'),
('03.Mar.2019', '0:30'),
('03.Mar.2019', '10:30');
And the desired results are below:
datetime1
01.Mar.2019 11:30:00
02.Mar.2019 01:30:00
03.Mar.2019 00:30:00
03.Mar.2019 10:30:00

SELECT STR_TO_DATE(CONCAT(date1,' ',time1),'%d.%b.%Y %H:%i') x FROM t1;
+---------------------+
| x |
+---------------------+
| 2019-03-01 11:30:00 |
| 2019-03-02 01:30:00 |
| 2019-03-03 00:30:00 |
| 2019-03-03 10:30:00 |
+---------------------+
4 rows in set (0.00 sec)

Although I feel that the way you are storing these values is not the best solution, you can present the data in its current stored format as a DATETIME by using CONCAT to join the separate VARCHARs together and then STR_TO_DATE to convert the string into a DATETIME:
SELECT STR_TO_DATE(CONCAT(date1, ' ', time1), '%d.%b.%Y %k:%i') FROM t1;
This is broken into two parts:
CONCAT(date1, ' ', time1)
Joins the date and time together with a space into a single string that will look like this:
01.Mar.2019 11:30
02.Mar.2019 1:30
03.Mar.2019 0:30
03.Mar.2019 10:30
Then, STR_TO_DATE converts this to a DATETIME using format specifiers:
STR_TO_DATE(CONCAT(date1, ' ', time1), '%d.%b.%Y %k:%i')
So, the formats are:
%d - Day of the month with leading zero if it is 1 number (01, 02, 03, and so on)
%b - Three-characters abbreviated month name (Jan, Feb, Mar, and so on)
%Y - Four digits year (2018, 2019, and so on)
%k - Hour in 24-hour format without leading zero (0, 1, 2, and so on)
%i - Minutes with leading zero (00, 01, 02, and so on)
The output from this will be:
2019-03-01 11:30:00
2019-03-02 01:30:00
2019-03-03 00:30:00
2019-03-03 10:30:00
I just want to add that I feel that the best way to store date and time information in the database is almost certainly to use a DATETIME column.

Related

convert date into mysql datetime format

I have datetime in the following format in a csv data
In_Time
1/1/17 1:07 AM
1/1/17 12:59 PM
I am unable to load data with a column that holds values like above. SO I loaded the data in text format for the In_Time column and I am trying to use STR_TO_DATE() function to now convert the column into a datetime column in mysql.
I am trying the below code but it gives me error:
Incorrect datetime value: '1/1/17 12:27 AM' for function str_to_date
UPDATE mytable
SET In_Time = STR_TO_DATE(ED_Arrival_Time, '%d/%m%y %h: %i: %p');
Please help.
There is no such time as 12:59 PM however given the correct formatting options for str_to_date https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format for the dates passed the result will be null and no error is thrown
DROP TABLE IF EXISTS T;
create table t
( ED_Arrival_Time varchar(20), In_Time datetime);
insert into t values
('1/1/17 1:07 AM',null),('1/1/17 11:59 PM',null),('1/1/17 23:59 PM',null);
select ED_Arrival_Time, str_to_date(ed_arrival_time,'%d/%m/%y %h:%i %p')
from t;
+-----------------+--------------------------------------------------+
| ED_Arrival_Time | str_to_date(ed_arrival_time,'%d/%m/%y %h:%i %p') |
+-----------------+--------------------------------------------------+
| 1/1/17 1:07 AM | 2017-01-01 01:07:00 |
| 1/1/17 11:59 PM | 2017-01-01 23:59:00 |
| 1/1/17 23:59 PM | NULL |
+-----------------+--------------------------------------------------+
3 rows in set, 1 warning (0.001 sec)
The expectation is that all the incoming dates are in the same format - if not then you need to cleanse them.
BTW load data infile can manipulate data loading from a csv file see the section Input Preprocessing in the manual https://dev.mysql.com/doc/refman/8.0/en/load-data.html
As a general principle, it's good to break the problem down into the smallest part that is causing a problem and solve that. In this case, I think that is the format specifier for the STR_TO_DATE() function.
Find a list of format specifiers: https://www.w3schools.com/sql/func_mysql_str_to_date.asp
Open a MySQL terminal, then iteratively try it with a few of your strings until you get the correct format specifier string which should be something like this:
select str_to_date('1/1/17 1:07 AM', '%e/%c/%y %I:%i %p') as test_date_parse;
Then adjust your code with the correct date specifier.

Format Date from Wednesday 17th May 2017 to 17/05/2017 format in SQL

The dates in my table are formatted like this Wednesday 17th May 2017 and Saturday 27th May 2017 and I want to convert it to something like this 17/05/2017 and 27/05/2017 and ORDER BY MyDate.
I tried doing it many different ways and did a lot of research for hours but no luck.
$sql="SELECT * FROM table
WHERE 1 = CASE WHEN deliver = 'Completed' THEN 0 ELSE order = '$order' END
ORDER BY STR_TO_DATE(MyDate,"d-m-Y") ASC";
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['MyDate'];
}
If someone could please help, I would very much appreciate it.
You need to use a proper format when converting string to datetime values
SELECT *,
-- convert to datetime and then format accordingly
DATE_FORMAT(STR_TO_DATE(mydate, '%W %D %M %Y'), '%m/%d/%Y') formatted_date
FROM table1
-- convert to datetime
ORDER BY STR_TO_DATE(mydate, '%W %D %M %Y');
%W - Weekday name (Sunday..Saturday)
%D - Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%M - Month name (January..December)
%Y - Year, numeric, four digits
Sample output:
+------+-------------------------+----------------+
| id | mydate | formatted_date |
+------+-------------------------+----------------+
| 2 | Wednesday 17th May 2017 | 05/17/2017 |
| 1 | Saturday 27th May 2017 | 05/27/2017 |
+------+-------------------------+----------------+
Here is a dbfidlle demo

How to convert DATETIME to TIMESTAMP in mysql?

I have DATETIME column in my table, with 2015-04-23 11:17:49 properties
Trying to convert it to unix timestamp, acording to the mysql documentation I need just put the field into UNIX_TIMESTAMP() function and I'll get -> 1223423442 - timestamp but it's doesn't work, I've got only 0000-00-00 00:00:00
Tried a lot of stuff:
// doesn't work
UNIX_TIMESTAMP(CAST(`updated` AS CHAR(100))) AS updated_at,
// doesn't work
UNIX_TIMESTAMP(`updated`) AS updated_at,
//doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(CAST(`created` AS CHAR(100)), \'%M %e %Y %h:%i%p\'))
AS created_at'
// doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(`created`, '%M %e %Y %h:%i%p'))
AS created_at
Without `` doesn't work as well, am I missing something?
Try:
select
o1.id,
o1.operation_date_time,
(unix_timestamp(o2.operation_date_time) - unix_timestamp(o1.operation_date_time))
as duration
from operations as o1
inner join operations as o2
where o1.operation = "START"
and o2.operation = "STOP"
and o1.id = (o2.id - 1);
It should give as output:
+------+---------------------+----------+
| id | operation_date_time | duration |
+------+---------------------+----------+
| 1 | 2000-01-01 06:30:45 | 4455 |
| 3 | 2000-01-01 08:18:12 | 11146 |
| 5 | 2000-01-01 15:45:01 | 11792 |
+------+---------------------+----------+
3 rows in set (0.00 sec)
I do not understand why do you need to convert DATETIME to TIMESTAMP.
You can use INT(11) field to store UNIX TIMESTAMPs converted from DATETIME using function UNIX_TIMESTAMP(your_datetime_field).
Note, according to documentation: http://dev.mysql.com/doc/refman/5.5/en/datetime.html
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Convert datetime column to 24 hour format

I have a column called schedule_time (datetime) format. I want to convert the time to 24 hour time.
2016-03-08 03:00:00 to 2016-03-08 15:00:00
Please note that DATETIME values are always stored in 24h format (http://dev.mysql.com/doc/refman/5.7/en/datetime.html). There is no AM/PM.
When you want to display the values, there is however the DATE_FORMAT
function, which will format the value according to your needs, including AM/PM:
select DATE_FORMAT(schedule_time, '%Y-%m-%d %h:%i:%s %p') from t1;
This will give 2016-03-08 03:00:00 AM and 2016-03-08 03:00:00 PM. But the values in the DB are still the same, in 24h format.
If adding 12 hours would solve your issue, the you can do it like this:
start transaction;
update t1 set schedule_time = date_add(schedule_time, interval 12 hour);
select * from t1; -- verify!!!
rollback;
-- or commit;
I put this in a transaction so you can first verify your results. If they are wrong, simply rollback the transaction (provided you use InnoDB tables). If you don't have transactions (or feel uncomfortable with them), you can undo the change with date_sub instead of date_add.
But be aware: This doesn't change from 12h to 24h format, it simply adds 12 hours to all your schedule_time values.
Use MySQL's DATE_FORMAT function.
The format string will be '%Y-%m-%d %T'.
Selecting the current date with 24-hour time:
mysql> SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %T') AS now
+---------------------+
| now |
+---------------------+
| 2016-03-08 20:47:04 |
+---------------------+
1 row in set (0.00 sec)
Selecting a date with 24-hour time from a table:
mysql> SELECT DATE_FORMAT(`created_at`, '%Y-%m-%d %T') AS created_at FROM test.comments;
+---------------------+
| created_at |
+---------------------+
| 2016-02-25 16:32:12 |
+---------------------+
1 row in set (0.00 sec)

I have a datetime, and i need to see if this datetime is between two other times

In my MySQL table , I have two time datatype columns storing a starttime value( (01:00:00) (call it B) and an endtime value (07:00:00) (call it C) for a record.
In my form, I collect a date and time from user and convert this to a datetime in my code (call it A), then in mySQL query I query for all records where A is between B and C
Select * from targetTBL where #pickupdatetime# between B and C
the problem is that when I do a dump of the time values B,C, they show up as 1970-01-01 01:00:00 and 1970-01-01 07:00:00
Ideally, I would like to compare just the time portion.
Ex.
A = 2014-03-18 07:00:00
where 07:00:00 between 01:00:00 and 07:00:00
instead of
where 2014-03-18 07:00:00 between 1970-01-01 01:00:00 and 1970-01-01 07:00:00
but when I do the date math using compare, I think that the date arithmetic is off because of the date part.
Is it possible to do something like this in a query using just the time part?
where 07:00:00 between 01:00:00 and 07:00:00
I am getting a result , I just don't trust it...
Try
WHERE timevalue BETWEEN time(field1) AND time(field2)
MySQL has a LARGE number of date/time-specific functions just for this sort of thing: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
You may try this
Select * from targetTBL where hour(#pickupdatetime#) between B and C