时间戳是数据库常用的存放日期的形式之一,表示从 UTC 时间’1970-01-01 00:00:00’开始到现在的秒数,与常规时间格式如 ‘2018-01-01 00:00:00’可以相互转换,方法如下。

一、unix_timestamp 函数用法

1、unix_timestamp() 返回当前时间戳。另外,current_timestamp() 也有同样作用。

2、unix_timestamp(string date) 返回 date 对应的时间戳,date 格式必须为 yyyy-MM-dd HH:mm:ss。

hive> select unix_timestamp('2018-06-29 00:00:00');

OK

1530201600

3、unix_timestamp(string date, string format) 返回 date 对应的时间戳,date 格式由 format 指定。

hive> select unix_timestamp('2018/06/29 09', 'yyyy/MM/dd HH');

OK

1530234000

二、from_unixtime 函数用法

1、from_unixtime(int/bigint timestamp) 返回 timestamp 时间戳对应的日期,格式为 yyyy-MM-dd HH:mm:ss。

hive> select from_unixtime(1000000000);

OK

2001-09-09 09:46:40

2、from_unixtime(int/bigint timestamp, string format) 返回 timestamp 时间戳对应的日期,格式由 format 指定。

hive> select from_unixtime(1000000000, 'yyyy/MM/dd HH');

OK

2001/09/09 09

三、“毫秒”时间戳的特殊处理

有时候,存放的时间戳不是秒数,而是毫秒数,因此转换前需要除以1000。

同理,时间转成时间戳时,也需要乘以 1000。

select

timestamps,

from_unixtime(cast(timestamps/1000 as int))

from

test_table

如何辨别时间戳是秒数还是毫秒数

2001-09-09 09:46:40 ~ 2286-11-21 01:46:40 之间的时间戳,都是10位数。 因此,我们这个时代使用的时间戳一般都是10位。如果遇到13位的时间戳,则为毫秒数。

文章来源: https://www.2cto.com/database/201806/757785.html

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: