bash 如何将结果 /bin/date "%Y-%m-%d %H:%M:%S" 转换为秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29446192/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:54:57  来源:igfitidea点击:

How to covert the result /bin/date "%Y-%m-%d %H:%M:%S" into seconds?

bashdateenvironment-variables

提问by marcos barcelona

How can I convert a date variable to seconds?

如何将日期变量转换为秒?

I have a variable called CDATE defined like this:

我有一个名为 CDATE 的变量,定义如下:

CDATE=$(/bin/date +"%Y-%m-%d %H:%M:%S")

CDATE example output: "2012-12-12 12:12:12"

CDATE 示例输出:“2012-12-12 12:12:12”

I would like to convert this to time in seconds and save it in another variable.

我想将其转换为以秒为单位的时间并将其保存在另一个变量中。

回答by Cyrus

x=($(date +"%Y-%m-%d %H:%M:%S %s"))
CDATE="${x[0]} ${x[1]}"
secs="${x[2]}"       # seconds since 1970-01-01 00:00:00 UTC
echo $CDATE
echo $secs

Output:

输出:

2015-04-04 14:13:08
1428149588

回答by weibeld

On Linux:

在 Linux 上:

CDATE=$(date "+%Y-%m-%d %H:%M:%S")
SECONDS=$(date -d "$CDATE" +%s)

On Mac:

在 Mac 上:

CDATE=$(date "+%Y-%m-%d %H:%M:%S")
SECONDS=$(date -j -f "%Y-%m-%d %H:%M:%S" "$CDATE" +%s)

And the content of the two variables is (in both cases):

并且两个变量的内容是(在两种情况下):

$ echo "$CDATE"
2015-04-04 16:24:41

$ echo "$SECONDS"
1428157497

回答by Michael Jaros

If you are not charged for CPU time, then I would call datetwice to make it more readable:

如果您不为 CPU 时间付费,那么我会调用date两次以使其更具可读性:

# get the timestamp:
timestamp=$( date +"%s" )

# format it:
CDATE=$( date -d @"$timestamp" +"%Y-%m-%d %H:%M:%S" )

echo "$CDATE"
echo "$timestamp"

回答by Tiago Lopo

The simplest way:

最简单的方法:

source  <(date +"CDATE='%Y-%m-%d %H:%M:%S' EPOCH='%s'")

Example:

例子:

tiago@dell:/tmp$ source  <(date +"CDATE='%Y-%m-%d %H:%M:%S' EPOCH='%s'")
tiago@dell:/tmp$ echo "cdate:$CDATE epoch:$EPOCH"
cdate:2015-04-05 12:39:58 epoch:1428233998