100. Timestamp 相关函数
正如您从下面的示例中看到的,systime()
返回 POSIX 纪元时间中的时间,即自 1970 年 1 月 1 日以来经过的秒数。
$ awk 'BEGIN { print systime() }'
1299345651
当您使用 strftime
函数将纪元时间转换为可读格式时,systime
函数变得更加有用。
以下示例使用 systime
和 strftime
函数以可读格式显示当前时间戳。
$ awk 'BEGIN { print strftime("%c",systime()) }'
Sat 05 Mar 2011 09:21:10 AM PST
以下 awk 脚本显示了各种可能的日期格式。
$ cat strftime.awk
BEGIN {
print "--- basic formats --"
print strftime("Format 1: %m/%d/%Y %H:%M:%S",systime())
print strftime("Format 2: %m/%d/%y %I:%M:%S %p",systime())
print strftime("Format 3: %m-%b-%Y %H:%M:%S",systime())
print strftime("Format 4: %m-%b-%Y %H:%M:%S %Z",systime())
print strftime("Format 5: %a %b %d %H:%M:%S %Z %Y",systime())
print strftime("Format 6: %A %B %d %H:%M:%S %Z %Y",systime())
print "--- quick formats --"
print strftime("Format 7: %c",systime())
print strftime("Format 8: %D",systime())
print strftime("Format 8: %F",systime())
print strftime("Format 9: %T",systime())
print strftime("Format 10: %x",systime())
print strftime("Format 11: %X",systime())
print "--- single line format with %t--"
print strftime("%Y %t%B %t%d",systime())
print "--- multi line format with %n --"
print strftime("%Y%n%B%n%d",systime())
}
$ awk -f strftime.awk
--- basic formats --
Format 1: 03/05/2011 09:26:03
Format 2: 03/05/11 09:26:03 AM
Format 3: 03-Mar-2011 09:26:03
Format 4: 03-Mar-2011 09:26:03 PST
Format 5: Sat Mar 05 09:26:03 PST 2011
Format 6: Saturday March 05 09:26:03 PST 2011
--- quick formats --
Format 7: Sat 05 Mar 2011 09:26:03 AM PST
Format 8: 03/05/11
Format 8: 2011-03-05
Format 9: 09:26:03
Format 10: 03/05/2011
Format 11: 09:26:03 AM
--- single line format with %t--
2011 March 05
--- multi line format with %n --
2011
March
05
以下是您可以在 strftime
函数中使用的各种时间格式标识符。请注意,下面显示的所有缩写都取决于您的区域设置。这些示例显示的是英语 (en)。
格式标识符 | 描述 |
---|---|
%m |
两位数字格式的月份。 一月显示为 01 |
%b |
月份缩写。 一月显示为 Jan |
%B |
月份已完全显示。 一月显示为一月。 |
%d |
天,采用两位数字格式。 该月的 4 号显示为 04。 |
%Y |
四位数格式的年份。 例如:2011年 |
%y |
两位数字格式的年份。 2011 年显示为 11。 |
%H |
24 小时格式的小时。 下午 1 点显示为 13 |
%l |
12 小时格式的小时。 下午 1 点显示为 01。 |
%p |
显示上午或下午。 将此与 %I 12 小时格式一起使用。 |
%M |
两个字符格式的分钟。 9 分钟显示为 09。 |
%S |
秒,采用两个字符格式。 5秒显示为05 |
%a |
以三个字符格式显示一周中的某一天。 星期一显示为星期一。 |
%A |
完整显示一周中的某一天。 星期一显示为星期一。 |
%Z |
时区。 太平洋标准时间显示为 PST。 |
%n |
显示换行符 |
%t |
显示制表符 |
快速时间格式:
格式标识符 | 描述 |
---|---|
%c |
以当前区域设置完整格式显示日期。 例如:太平洋标准时间 2011 年 2 月 11 日星期五上午 02:45:03 |
%D |
快速日期格式。 与 %m/%d/%y 相同 |
%F |
快速日期格式。 与 %Y-%m-%d 相同 |
%T |
快速时间格式。 与 %H:%M:%S 相同 |
%x |
日期格式基于您的区域设置。 |
%X |
时间格式基于您的区域设置。 |