Convert human readable time into EPOCH using shell script

吃可爱长大的小学妹 提交于 2020-01-04 11:11:15

问题


I have a human readable time as

08-18-2016 09:18:25

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

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

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


回答1:


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’

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

So this works:

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

Or using variables:

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



回答2:


Thanks for the explanation fedorqui. But 1471511905 is the epoch time for 08 18 2016 09:18:25, not 1471504705. – Mohit Rane

date -u … will print Coordinated Universal Time.



来源:https://stackoverflow.com/questions/39016126/convert-human-readable-time-into-epoch-using-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!