如何修改jq代码将日期格式从YYYYMMDD转为YYYY-MM-DD?
解决jq日期格式转换问题
问题背景
原始jq代码:
echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date ), at ten o clock"'
当前输出:
The bus will be here on 20200101, at ten o clock The bus will be here on 20210101, at ten o clock
期望将日期格式从20200101改为2020-01-01,得到目标输出:
The bus will be here on 2020-01-01, at ten o clock The bus will be here on 2021-01-01, at ten o clock
直接使用strftime时触发错误:
尝试代码:
echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date | strftime("%Y-%m-%d") ), at ten o clock"'
错误信息:
jq: error (at <stdin>:1): strftime/1 requires parsed datetime inputs
解决方案
方法1:先解析日期字符串再格式化
strftime仅支持已解析的datetime对象作为输入,因此需要先用strptime将8位日期字符串转换为jq可识别的datetime类型,再进行格式化:
echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date | strptime("%Y%m%d") | strftime("%Y-%m-%d") ), at ten o clock"'
strptime("%Y%m%d"):把20200101格式的字符串解析为datetime对象strftime("%Y-%m-%d"):将datetime对象转换为YYYY-MM-DD格式的字符串
方法2:字符串截取拼接(适用于固定格式日期)
如果日期始终是8位固定结构(4位年+2位月+2位日),可以直接通过字符串截取拼接得到目标格式:
echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date[:4] + "-" + .date[4:6] + "-" + .date[6:] ), at ten o clock"'
.date[:4]:截取前4位作为年份.date[4:6]:截取第5-6位作为月份.date[6:]:截取最后2位作为日期- 用
-拼接三部分得到目标格式
内容的提问来源于stack exchange,提问作者fuumind
相关产品推荐
相关产品推荐

