Bash 将日期转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25619923/
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
Bash convert date to timestamp
提问by Lenny
I have a date in format 'YYYYMMDDHHMMSS'
and I need to convert it to Unix timestamp.
我有一个格式的日期,'YYYYMMDDHHMMSS'
我需要将其转换为 Unix 时间戳。
I tried to date -d '20140826225834'
but I get 'invalid date'
error. I asume that I would have to convert what I have ( 20140826225834
) to accepted date and then convert it to timestamp?
Edit: I have sed this date from 2014-08-21_23.03.07
- maybe it would be easier to convert this date type
我尝试过,date -d '20140826225834'
但'invalid date'
出现错误。我假设我必须将我拥有的 ( 20140826225834
) 转换为接受日期,然后将其转换为时间戳?编辑:我已经将这个日期从2014-08-21_23.03.07
- 也许转换这个日期类型会更容易
回答by fedorqui 'SO stop harming'
You should probably change the format of the date you get, so that date
can handle it. I change it to a YYYY/MM/DD HH:MM:SS
format with sed
.
您可能应该更改您获得的日期的格式,以便date
可以处理它。我将其更改为YYYY/MM/DD HH:MM:SS
带有sed
.
$ date -d"$(sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#// ::#' <<< "20140826225834")" "+%s"
1409086714
By pieces:
按件数:
$ sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#// ::#' <<< "20140826225834"
2014/08/26 22:58:34
$ date -d"2014/08/26 22:58:34"
Tue Aug 26 22:58:34 CEST 2014
$ date -d"2014/08/26 22:58:34" "+%s"
1409086714
回答by hek2mgl
You could use PHP, since PHP's strtotime()
can parse your input format:
您可以使用 PHP,因为 PHPstrtotime()
可以解析您的输入格式:
#!/bin/bash
input="20140826225834"
output=$(php -r 'echo strtotime("'"$input"'");')
echo "$output" # 1409086714