将日期转换为MySQL日期时间格式

qyuhtwio  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(207)

我在CSV数据中有以下格式的DateTime

In_Time
1/1/17 1:07 AM
1/1/17 12:59 PM

我无法使用包含上述值的列加载数据。因此,我以文本格式加载了in_time列的数据,并尝试使用str_to_date()函数将该列转换为MySQL中的DateTime列。

我正在尝试以下代码,但出现错误:

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');

请帮帮忙。

piztneat

piztneat1#

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.

7lrncoxx

7lrncoxx2#

没有12:59 PM这样的时间,但是,如果传递的日期的str_to_https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format的格式选项正确,则结果将为空,并且不会引发任何错误

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)

期望所有传入的日期都是相同的格式-如果不是,则需要清除它们。

顺便说一句,加载数据文件可以操作从CSV文件加载数据,请参阅手册https://dev.mysql.com/doc/refman/8.0/en/load-data.html中的输入预处理一节

相关问题