[英]How to convert Text Column to Date Column in SQL?
I was given a date column in the form of 'YYYY-MM-dd HH:mm:ss UTC'.我得到了一个格式为“YYYY-MM-dd HH:mm:ss UTC”的日期列。 I have tried using cast and convert to date, datetime, and timestamp, but they all only return the YYYY.
我尝试使用强制转换并转换为日期、日期时间和时间戳,但它们都只返回 YYYY。 Is there any way to return the date correctly from this type of string?
有没有办法从这种类型的字符串中正确返回日期? I also would like this NewDate column to be added to my table for future use.
我还希望将此 NewDate 列添加到我的表中以备将来使用。
Below is the code I have tried下面是我试过的代码
select OrigDate, cast(OrigDate as timestamp) as NewDate from MyTable
SQLite has no special datatype for dates, which can be stored as text or numbers (julian days or epoch timestamp); SQLite 没有特殊的日期数据类型,可以存储为文本或数字(儒略日或纪元时间戳); instead, it has a set of date and time functions that operate on these values.
相反,它有一组对这些值进行操作的日期和时间函数。
SQLite recognizes 'YYYY-MM-DD HH:MM:SS'
as a valid date format, so to make your strings valid SQLite date formats, you just need to remove the trailing " UTC": SQLite 将
'YYYY-MM-DD HH:MM:SS'
识别为有效的日期格式,因此要使您的字符串成为有效的 SQLite 日期格式,您只需删除尾随的“UTC”:
select OrigDate, substring(OrigDate, -4) NewDate from mytable
You can add the new column with name NewDate
to the table like this:您可以将名为
NewDate
的新列添加到表中,如下所示:
alter table MyTable add NewDate text;
As you can see the data type defined is text
because there is no date
or datetime
data type in SQLite.正如您所看到的,定义的数据类型是
text
因为 SQLite 中没有date
或datetime
数据类型。
Then you can populate/update this column with the local time that each of your UTC datetimes already have in the column OrigDate
with the use of the function datetime()
:然后,您可以使用函数
datetime()
使用OrigDate
列中每个UTC日期时间已经具有的本地时间填充/更新此列:
update MyTable
set NewDate = datetime(substr(OrigDate, 1, 19), 'localtime');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.