简体   繁体   English

如何在 SQL 中将时间戳转换为日期?

[英]How to convert timestamp to date in SQL?

Image: http://i.stack.imgur.com/CyyHo.jpg图片: http : //i.stack.imgur.com/CyyHo.jpg

I have a dataset as shown in the image.我有一个如图所示的数据集。 I want to use the values of created_date column as datetime format.我想使用 created_date 列的值作为datetime格式。 How can i do that?我怎样才能做到这一点?

The time you would like to convert is called Unix timestamp , which means how many seconds have passed since 1970/01/01.您想要转换的时间称为Unix timestamp ,这意味着自 1970/01/01 以来已经过去了多少秒。 In this occasion you will have to use DATA function, which will take the total number of seconds and add them to 1970/01/01.在这种情况下,您将不得不使用DATA函数,它将获取总秒数并将它们添加到 1970/01/01。

In SQL it is done in the following way:在 SQL 中,它通过以下方式完成:

select DATEADD(s, dateTimeInSeconds, '19700101')

Where s is Seconds and dateTimeInSeconds is your value of date;其中s是秒,而 dateTimeInSeconds 是您的日期值; '19700101' is a starting point. '19700101'是一个起点。

Is created_date of type 'epoch'? created_date 是 'epoch' 类型吗? And are you trying to use the datetime format within the SQL database or within your business logic?您是否尝试在 SQL 数据库或业务逻辑中使用日期时间格式? If it is in the business logic, it then depends on the language you use.如果它在业务逻辑中,则取决于您使用的语言。 I'd love to help but I don't fully understand the use case.我很乐意提供帮助,但我不完全了解用例。 If you could provide more information that would help us help you!如果你能提供更多的信息来帮助我们帮助你!

Cheers!干杯!

It doesn't look like unix timestamp but datetime without some chars (just digits are left).它看起来不像unix时间戳,而是没有一些字符的日期时间(只剩下数字)。

To get "real" timestamp use in MySql: unix_timestamp()在 MySql 中使用“真实”时间戳: unix_timestamp()

To convert "real" timestamp to datetime use in MySql: FROM_UNIXTIME()将“真实”时间戳转换为 MySql 中的日期时间使用:FROM_UNIXTIME()

To convert your column to datetime use:要将您的列转换为日期时间,请使用:

    CONCAT(SUBSTR(created_date, 1, 4),
        '-',
        SUBSTR(created_date, 5, 2),
        '-',
        SUBSTR(created_date, 6, 2),
        ' ',
        SUBSTR(created_date, 7, 2),
        ':',
        SUBSTR(created_date, 11, 2),
        ':',
        SUBSTR(created_date, 13, 2))

Column values does not seems to be a TimeStamp.列值似乎不是时间戳。 Use the below script to make the values as datetime .使用以下脚本将值设置为 datetime 。

    SELECT credits,amount,city,
                  CONVERT(DATETIME,LEFT(created_date,8)
                  +' '+SUBSTRING(created_date,9,2)
                  +':'+SUBSTRING(created_date,11,2)
                  +':'+RIGHT(created_date,2)) Created_Date
    FROM YourTable 

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

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