简体   繁体   English

如何将 UNIX TIME 转换为 SQL 日期时间格式

[英]How to convert the UNIX TIME into SQL datetime format

select COUNT(DISTINCT devices) AS "Devices" from measure_tab where 
  measure_tab.time >= 1375243200 and 
  measure_tab.time < 1375315200;

The output of the above sql query gives a table with a column named "Devices" with number of devices.上述 sql 查询的输出给出了一个表,其中包含一个名为“设备”的列,其中包含设备数量。 I want the time which is one of the attributes of measure_tab should also get displayed in another column of the output table with the UNIX TIME which is 1375243200 in this query converted into the SQL datetime format which is Thu Aug 1 00:00:00 UTC 2013 .我希望作为 measure_tab 属性之一的时间也应该显示在输出表的另一列中,UNIX TIME 在此查询中为 1375243200,转换为 SQL 日期时间格式,即Thu Aug 1 00:00:00 UTC 2013

Can someone help me out?有人可以帮我吗?

Thanks谢谢

You can use function as below:您可以使用以下功能:

select FROM_UNIXTIME(UNIX_TIMESTAMP(),'%a %b %d %H:%i:%s UTC %Y');

output will be:输出将是:

'Wed Feb 05 05:36:16 UTC 2014'

In your query在您的查询中

select COUNT(DISTINCT devices) AS "Devices",
  FROM_UNIXTIME(measure_tab.time,'%a %b %d %H:%i:%s UTC %Y') as d from measure_tab where 
  measure_tab.time >= 1375243200 and 
  measure_tab.time < 1375315200;

For more info you can check documentation: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime有关更多信息,您可以查看文档: http : //dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

You can see sql fiddle: http://sqlfiddle.com/#!2/a2581/20357可以看到sql fiddle: http ://sqlfiddle.com/#!2/a2581/ 20357

In Mysql you can use from_unixtime() function to convert unix timestamp to Date :在 Mysql 中,您可以使用from_unixtime()函数将 unix 时间戳转换为Date

select COUNT(DISTINCT devices) AS "Devices" from measure_tab where 
  measure_tab.time >= from_unixtime(1375243200) and 
  measure_tab.time < from_unixtime(1375315200);

you could use FROM_UNIXTIME inside DATE_FORMAT , but luckily, FROM_UNIXTIME also accepts a format string, so you could just use it by itself您可以在DATE_FORMAT 中使用FROM_UNIXTIME ,但幸运的是, FROM_UNIXTIME 也接受格式字符串,因此您可以单独使用它

Like this像这样

SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x') SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x')

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')

As detailed in the other answers, FROM_UNIXTIME is the function you are looking for.如其他答案中所述, FROM_UNIXTIME是您正在寻找的函数。 Please be aware that this implicitly takes into account the local time zone setting on the machine running MySQL.请注意,这隐含地考虑了运行 MySQL 的机器上的本地时区设置。

There's lots of useful information here:这里有很多有用的信息:

Should MySQL have its timezone set to UTC? MySQL 是否应该将其时区设置为 UTC?

if you need to find out how to check/set the time zone.如果您需要了解如何检查/设置时区。

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

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