bash 如何使用bash转换日期HH:MM:SS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16414632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert a date HH: MM: SS in second with bash?
提问by MaxGeneGrim
How to convert a date HH: MM: SS in second with bash?
如何使用bash转换日期HH:MM:SS?
Knowing that this is a date that I recovered in a file so I can't take it in another format.
知道这是我在文件中恢复的日期,因此我无法将其转换为其他格式。
I have two variables $DateStart and $DateEnd and i would like the difference between both.
我有两个变量 $DateStart 和 $DateEnd ,我想知道两者之间的区别。
采纳答案by Kent
date +%s
returns the current datetime in seconds since 1970-01-01 00:00:00 UTC
返回自 1970-01-01 00:00:00 UTC 以来的当前日期时间(以秒为单位)
if you want to get a given datetime in seconds since 1970-01-01 00:00:00 UTC, for example:
如果要获取自 1970-01-01 00:00:00 UTC 以来的给定日期时间(以秒为单位),例如:
kent$ date -d"2008-08-08 20:20:20" +%s
1218219620
to get diff in seconds, you just get the two dates in seconds, and do a s1-s2
要在几秒钟内获得差异,您只需在几秒钟内获得两个日期,然后执行 s1-s2
回答by Erik van Oosten
On a Mac you can convert a date into another date with a combination of the -j
and -f
option:
在 Mac 上,您可以使用-j
和-f
选项的组合将日期转换为另一个日期:
$ date -j -f '%Y-%m-%d %H:%M:%S' "2016-02-22 20:22:14" '+%s'
1456168934
Where -j
suppresses changing the system clock,
-f <fmt>
gives the format to use for parsing the given date,
"2016-02-22 20:22:14"
is the input date and
+<fmt>
is the output format.
其中-j
抑制更改系统时钟,
-f <fmt>
给出用于解析给定日期的格式,
"2016-02-22 20:22:14"
是输入日期,
+<fmt>
是输出格式。
回答by spbnick
Assuming the time in HH:MM:SS format is in variable time_hhmmss
and time in
seconds needs to be stored in time_s
:
假设 HH:MM:SS 格式的time_hhmmss
时间是可变的,并且需要以秒为单位的时间存储在time_s
:
IFS=: read -r h m s <<<"$time_hhmmss"
time_s=$(((h * 60 + m) * 60 + s))
回答by bolD
Try to use my solution with sed+awk:
尝试将我的解决方案与 sed+awk 一起使用:
echo $DateStart | sed 's/:\|-/ /g;' | awk '{print " "" "" "}' | awk '{print +*60+*3600+*86400}'
echo $DateEnd | sed 's/:\|-/ /g;' | awk '{print " "" "" "}' | awk '{print +*60+*3600+*86400}'
it splits the string with sed, then inverts the numbers backwards ("DD hh mm ss" -> "ss mm hh DD") and calculates them with awk. It works even you add days: [[DD-]hh:]mm:ss, eg:
它用 sed 拆分字符串,然后将数字向后反转(“DD hh mm ss”->“ss mm hh DD”)并用 awk 计算它们。即使您添加天数也有效:[[DD-]hh:]mm:ss,例如:
34:56 12:34:56 123-12:34:56
34:56 12:34:56 123-12:34:56