Bash convert date to timestamp

旧时模样 提交于 2020-01-24 08:08:07

问题


I have a date in format 'YYYYMMDDHHMMSS' and I need to convert it to Unix timestamp.

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


回答1:


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 -d"$(sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#\1/\2/\3 \4:\5:#' <<< "20140826225834")" "+%s"
1409086714

By pieces:

$ sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#\1/\2/\3 \4:\5:#' <<< "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



回答2:


You could use PHP, since PHP's strtotime() can parse your input format:

#!/bin/bash

input="20140826225834"
output=$(php -r 'echo strtotime("'"$input"'");')

echo "$output" # 1409086714


来源:https://stackoverflow.com/questions/25619923/bash-convert-date-to-timestamp

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