Bash将字符串转换为时间戳 [英] Bash convert string to timestamp
问题描述
我有一个格式为 20141225093000
的字符串,它表示 2014年12月25日09:30:00
,我想将原始格式转换为unix时间戳格式,所以我可以对其进行时间操作.我该如何在bash中执行此操作?
I have a string in format 20141225093000
which represents Dec 25, 2014 09:30:00
and I want to convert the original format to a unix timestamp format so i can do time operations on it.How would I do this in bash?
我可以轻松地使用 expr
解析出这些值,但我希望能够识别出诸如YYYYmmddHHMMSS之类的格式,然后根据该格式进行转换.
I can easily parse out the values with expr
but I was hoping to be able to identify a format like YYYYmmddHHMMSS and then convert it based on that.
推荐答案
使用GNU日期,您可以将 YYYY-MM-DDTHH:MM:SS
转换为纪元时间(从1-1-开始的秒数)1970),就像这样:
With GNU date, you can convert YYYY-MM-DDTHH:MM:SS
to epoch time (seconds since 1-1-1970) easily, like so:
date -d '2014-12-25T09:30:00' +%s
要在没有任何分隔符的情况下开始执行此操作:
To do this starting without any delimiters:
in=20141225093000
rfc_form="${in:0:4}-${in:4:2}-${in:6:2}T${in:8:2}:${in:10:2}:${in:12:2}"
epoch_time=$(date -d "$rfc_form" +%s)
这篇关于Bash将字符串转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!