如何将 YYYYMMDDHHMMSS 转换为“date”可读的日期
我有一组 YYYYMMDDHHMMSS 格式的日期/时间字符串,我想将其转换为 date
实用程序可读的内容。通常,我可以这样做:
date -d "2010-10-01 12:34:56"
但是,date
不喜欢 YYYYMMDDHHMMSS:
date -d "20100101123456"
..invalid date
因此,我可能需要将字符串改进为先前的格式。我认为 sed 就是答案,但它很快就会变得丑陋。我非常确定我的字符串将是正确的格式,那么如何轻松地转换它们呢?
I have a set of date/time strings in the YYYYMMDDHHMMSS format that I want to convert to something readable by the date
utility. Usually, I can do something like:
date -d "2010-10-01 12:34:56"
However, date
does not like the YYYYMMDDHHMMSS:
date -d "20100101123456"
..invalid date
So, I probably need to refine the string to be in the prior format. I'm thinking sed
is the answer, but it gets ugly very fast. I'm quite certain my strings will be the proper format, so how do I easily convert them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
date 不允许“YYYYMMDDHHMMSS”,但它允许“YYYYMMDD HH:MM:SS”,所以:
date doesn't allow "YYYYMMDDHHMMSS", but it does "YYYYMMDD HH:MM:SS", so:
如果格式是完全固定的,你可以在 bash 中完成它,切碎字符串:
我不会费心尝试使用正则表达式 - 就像你说的,模式很快就会变得丑陋。大量重复
([0-9]{4})
,即使使用扩展或 perl 正则表达式也是如此。或者你可以灵活地匹配.
;没有验证。If the format is totally fixed, you could just do it within bash, chopping up the string:
I wouldn't bother trying to use regex - like you said, the pattern gets ugly fast. A lot of repetition of
([0-9]{4})
, even with extended or perl regex. Or you could be flexible and just match.
; no verification.所有这些正则表达式答案是怎么回事? date(1) 工具能够使用 strftime() 样式的日期格式...将一种日期类型转换为另一种日期类型的示例:
因此,如果它不是您想要的格式,请像这样转换然后使用它。如果您只想设置它,您可以简单地执行以下操作:
What's with all of these regular expression answers? The date(1) tool has the ability to use strftime() style date formatting... an an example of converting one date type to another:
So if it's not in the format you want, convert it like that and then use it. If you just want to set it, you can simply do:
试试这个:
结果:
您也想要一些连字符吗?
结果:
2010-11 :06:21:32:45
->2010-11-06:21:32:45
)2010-11-06 :21:32:45
->2010-11-06 21:32:45
)Try this:
Result:
You want some hyphens, too?
Result:
2010-11:06:21:32:45
->2010-11-06:21:32:45
)2010-11-06:21:32:45
->2010-11-06 21:32:45
)我承认这是拗口的。所有 . 最好应该是 [0-9] 或 \d,尽管我不记得 sed 是否支持后者。
I admit it'S a mouthful. All the .'s should optimally be [0-9] or \d, though I don't remember if sed supports the latter.
busybox date 或 bsd date 接受输入格式的描述。
Busybox 是一个 GNU 小型实用程序,易于安装。
bsd格式已经在另一个答案中介绍过了,所以这里是busybox:
Either busybox date or bsd date accept a description of the input format.
Busybox is a GNU small utility, easy to install.
The bsd format has been covered in another answer, so here is busybox: