简体   繁体   English

使用mysql查询将日期从'yyyy-dd-mm'转换为'yyyy-mm-dd'

[英]Convert date from 'yyyy-dd-mm' to 'yyyy-mm-dd' using mysql query

I am working on a database which has date fields in 'yyyy-dd-mm hh:mm' format, I used STR_TO_DATE to change the field to 'yyyy-mm-dd hh:mm' but it is giving back an error. 我正在开发一个数据库,其日期字段为'yyyy-dd-mm hh:mm'格式,我使用STR_TO_DATE将字段更改为'yyyy-mm-dd hh:mm',但它返回错误。

Query: 查询:

UPDATE transaction 
SET time_creation = STR_TO_DATE(time_creation, '%Y-%m-%d %H:%i');

Error: 错误:

Incorrect datetime value: '2005-08-06 15:57:00' for function str_to_date 函数str_to_date的日期时间值不正确:'2005-08-06 15:57:00'

I did a check with the following query too: 我也检查了以下查询:

SELECT 
   time_creation, 
   STR_TO_DATE(time_creation,'%Y-%m-%d %H:%i') AS DATE_FORMATTED 
FROM transaction;

and got NULL in the DATE_FORMATTED column for date values such as '2007-22-11 15:32' but worked fine for '2007-09-11 13:12' . 并在DATE_FORMATTED列中为'2007-22-11 15:32'等日期值获取NULL,但在'2007-09-11 13:12'工作正常。 I don't understand what exactly is happening. 我不明白究竟发生了什么。 Any help is appreciated.. thank you. 任何帮助表示赞赏..谢谢。

You have 你有

STR_TO_DATE(time_creation,'%Y-%m-%d %H:%i')

and you give '2007-22-11 15:32' which means 'yyyy- dd -* mm * hh:mm'. 你给'2007-22-11 15:32',意思是' yyyy - dd - * mm * hh:mm'。

Sql is trying to parse a date that contains the number 22 as month... Sql试图解析包含数字22的日期作为月...

Abyway Abyway

SELECT STR_TO_DATE('2005-08-06 15:57:00', '%Y-%m-%d %H:%i');

works fine in my mysql server. 在我的mysql服务器上正常工作。

First, you need to share the table definition with us. 首先,您需要与我们共享表定义。 It sounds like the column type for the time_creation field is a VARCHAR and not a DATETIME. 听起来time_creation字段的列类型是VARCHAR而不是DATETIME。 So you really should not try to store the result back into the same field. 所以你真的不应该试着把结果存回到同一个领域。 You want to save it into a valid DATETIME field so that the intrinsic column type is correct. 您希望将其保存到有效的DATETIME字段中,以便内部列类型正确。

Second, it sounds like some of your values are stored as YYYY-DD-MM and some as YYYY-MM-DD. 其次,听起来有些值存储为YYYY-DD-MM,有些值存储为YYYY-MM-DD。 Is that the case? 是这样的吗? If it is, you'll need more logic in order to differentiate between the values that are already correct and those that are not. 如果是,则需要更多逻辑才能区分已经正确的值和不正确的值。 If they are mixed, however, you are in a bit of a pickle because how do you know the proper way to interpret 2012-01-03? 然而,如果它们混合在一起,你会有点挑剔,因为你怎么知道解释2012-01-03的正确方法?

EDIT: 编辑:

Create a new DATETIME field (for the example I just use new_time_creation) and update like this: 创建一个新的DATETIME字段(例如我只使用new_time_creation)并像这样更新:

UPDATE transaction SET new_time_creation = STR_TO_DATE(time_creation, '%Y-%d-%m %H:%i');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM