Linux时间戳和标准时间的互转方法介绍



Linux时间戳和标准时间的互转方法介绍。在LINUX系统中,有许多场合都使用时间戳的方式表示时间,即从1970年1月1日起至当前的天数或秒数。如/etc/shadow里的密码更改日期和失效日期,还有代理服务器的访问日志对访问时间的记录等等。
下面介绍几种时间戳格式和标准时间格式转换的方法:
1、分别以标准格式和时间戳来显示当前时间
[root@365linux ~]# date
2010年 08月 10日 星期二 03:39:21 CST

[root@365linux ~]# date +%s

1281382775
2、显示指定时间的时间戳
[root@365linux ~]# date -d “2010-07-20 10:25:30″ +%s
1279592730
3、将时间戳转换为标准时间格式
方法1:使用date命令

[root@365linux ~]# date -d “@1279592730″

2010年 07月 20日 星期二 10:25:30 CST

[root@365linux ~]# date -d “1970-01-01 utc 1279592730 seconds”

2010年 07月 20日 星期二 10:25:30 CST

[root@365linux ~]# date -d “1970-01-01 14781 days” “+%Y/%m/%d %H:%M:%S”

2010/06/21 00:00:00

[root@localhost tmp]# date -d “@1279592730″

Tue Jul 20 10:25:30 CST 2010

[root@localhost tmp]# date -d “@1279592730″ +”%Y%m%d %H:%M:%S”

20100720 10:25:30

[root@localhost tmp]# date -d “@1279592730″ +”%F %H:%M:%S”

2010-07-20 10:25:30

[root@localhost tmp]# date -d “1970-01-01 utc 1279592730 seconds”

Tue Jul 20 10:25:30 CST 2010

[root@localhost tmp]# date -d “1970-01-01 utc 1279592730 seconds” +”%F %H:%M:%S” 2010-07-20 10:25:30


方法2:使用awk里的时间函数

[root@365linux ~]# echo “1279592730″ |awk ‘{print strftime (“%F %T”,$0)}’

2010-07-20 10:25:30

方法3:使用perl处理

[root@365linux ~]# perl -e ‘print localtime(1279592730).”\n”;’

Tue Jul 20 10:25:30 2010

补充:
关于时间格式的解释

UTC (Universal Time Coordinated,UTC)世界协调时间
CST (China Standard Time UTC+8:00)中国沿海时间(北京时间)
GMT (Greenwich Mean Time)格林威治标准时间:

系统时区设置:

[root@365linux ~]# vim /etc/sysconfig/clock ZONE=”Asia/Shanghai”

UTC=true

ARC=false

[root@365linux ~]# cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

————————————————————————————————————————————————————————–

oracle 中将unix/linux时间戳进行转换
unix/linux时间戳是按照从格林威治时间1970年1月1日期计算的一个秒数。

unix/linux时间戳转换为标准时间格式(主要是注意时区问题):
select TO_DATE(’19700101′,’yyyymmdd’) + 1235728935/86400 +TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone),1,3))/24 from dual 其中1235728935就是unix/linux时间戳,转换完之后就表示为 2009-2-27 18:02:15。

反过来也一样,还是要考虑时区:
select (to_date(’2009-2-27 18:02:15′,’yyyy-mm-dd hh24:mi:ss’) – to_date(’1970-1-1′,’yyyy-mm-dd’))*86400- TO_NUMBER(SUBSTR(