我正在尝试从系统中收集信息,我需要以小时和分钟的形式获取当前时间。
目前我有:
date | awk '{print $4}'
输出如下内容:
16:18:54
如何切断秒?
答案 0 :(得分:75)
提供格式字符串:
date +"%H:%M"
运行man date
将提供所有格式选项
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
%U week number of year, with Sunday as first day of week (00..53)
%V ISO week number, with Monday as first day of week (01..53)
%w day of week (0..6); 0 is Sunday
%W week number of year, with Monday as first day of week (00..53)
%x locale's date representation (e.g., 12/31/99)
%X locale's time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%z +hhmm numeric time zone (e.g., -0400)
%:z +hh:mm numeric time zone (e.g., -04:00)
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)
答案 1 :(得分:6)
对于您的问题,我有另一个解决方案。
在第一次使用 date
时,输出是这样的:
Thu 28 Jan 2021 22:29:40 IST
然后如果你只想以小时和分钟显示当前时间,你可以使用这个命令:
date | cut -d " " -f5 | cut -d ":" -f1-2
然后输出:
22:29
答案 2 :(得分:4)
你可以使用
date | awk '{print $4}'| cut -d ':' -f3
正如你刚才提到的那样只用date|awk '{print $4}'
命令就可以得到类似的东西
20:18:19
因此,我们可以看到是否要提取此字符串的某些部分,然后我们需要一个分隔符,对于我们的情况它是:
,因此我们决定在:
的基础上进行切割。
现在这个分隔符会将字符串分成三个部分,即20,18和19,因为我们想要在命令中使用第二个-f2。
总结一下,
cut
:根据分隔符填充一些字符串。
-d
:delimeter(此处:
)
-f2
:我们想要的切断标记。
答案 3 :(得分:1)
使用 bash 版本 >= 4.2:
printf "%(%H:%M)T\n"
或
printf -v foo "%(%H:%M)T\n"
echo "$foo"
见:man bash
答案 4 :(得分:0)
date +%H:%M
我认为会更容易:)。如果你真的想要砍掉秒,你就可以完成
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
答案 5 :(得分:-1)
还可能使用此脚本在变量中使用系统时间
now=$(date +"%m_%d_%Y_%M:%S")
输出为
12_07_2020_34:21