使用Shell脚本将人类可读的时间转换为EPOCH [英] Convert human readable time into EPOCH using shell script

查看:103
本文介绍了使用Shell脚本将人类可读的时间转换为EPOCH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的可读时间为

08-18-2016 09:18:25

我希望使用shell脚本将其转换为时代。

I want it to be converted into epoch time using shell script.

我尝试使用 date +%s ,但出现错误

I tried with date "+%s" but I am getting the error


日期:无效日期`08-18-2016 09:32:42'

date: invalid date `08-18-2016 09:32:42'


推荐答案

将日期时间转换为纪元的典型方法是使用:

The canonical way to convert a datetime into epoch is to use:

date "+%s"                    # for this moment's date
date -d" some date" "+%s"     # for a specific date

但是,在这种情况下,格式无效:

However, in this case the format is not valid:

$ date -d"08 18 2016 09:18:25" "+%s"
date: invalid date ‘08 18 2016 09:18:25’

您然后,需要先按摩一下字符串,然后再将其传递给 date -d

You need, then, to massage the string a bit before passing it to date -d.

这会转换两个字符串第一个空格变成斜线:

This converts the two first spaces into slashes:

$ sed 's# #/#;s# #/#' <<< "08 18 2016 09:18:25"
08/18/2016 09:18:25

因此可行:

$ date -d"$(sed 's# #/#;s# #/#' <<< "08 18 2016 09:18:25")" "+%s"
1471504705

或使用变量:

$ nice_date=$(sed 's# #/#;s# #/#' <<< "08 18 2016 09:18:25")
$ date -d"$nice_date" "+%s"
1471504705

这篇关于使用Shell脚本将人类可读的时间转换为EPOCH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆