问题
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