大网数据广告活动
服务器运维问答

Calculate seconds minutes and days ago in shell

· 52CE 我爱测

I have a timestamp that saves a user's last access information like Time => 14:15:05 PM Day => 08/23/2023 Based on this saved information, I would like to write a command that returns how much time has passed compared to the time…

问题原文

原帖链接 · Luana · CC BY-SA 4.0

I have a timestamp that saves a user's last access information like

Time => 14:15:05 PM

Day => 08/23/2023

Based on this saved information, I would like to write a command that returns how much time has passed compared to the time at now 15:15:14 PM on 8/23/2023 as the format below

=> 30 seconds ago

=> 12 minutes ago

=> 4 hours ago

=> 11 days ago

=> 1 year ago

what I've tried so far

date -d '7:00:00 AM - 15 minutes' '+%H:%M'

but this only returns 15 minutes ago based on the prescribed time of 7:00:00 AM an already defined time and decreasing its value to 15 minutes ago.

What I want is to calculate based on the actual time of now (23/08/2023 15:15:14 PM) and say how much time has passed since 14:15:05 on 23/08/2023 or the day before 22/08/2023.

已采纳解答

原帖链接 · glenn jackman · CC BY-SA 4.0

The date command cannot calculate durations.

It's essentially what I commented before:

  1. you have timestamp one: ts1=$( date -d "08/23/2023 14:15:05" "+%s" )

  2. you get a second timestamp, however you want ts2=$( date -d "now - 15 minutes" "+%s" )

  3. calculate the differences in different ways:

    $ printf '%(%F %T)T minus %(%F %T)T is %d %s\n' "$ts1" "$ts2" "$((ts1-ts2))" seconds
    2023-08-23 14:15:05 minus 2023-07-24 19:07:25 is 2574460 seconds
    
    $ printf '%(%F %T)T minus %(%F %T)T is %d %s\n' "$ts1" "$ts2" "$(( (ts1-ts2) / 60 ))" minutes
    2023-08-23 14:15:05 minus 2023-07-24 19:07:25 is 42907 minutes
    
    $ printf '%(%F %T)T minus %(%F %T)T is %d %s\n' "$ts1" "$ts2" "$(( (ts1-ts2) / (60*60) ))" hours
    2023-08-23 14:15:05 minus 2023-07-24 19:07:25 is 715 hours
    
    $ printf '%(%F %T)T minus %(%F %T)T is %d %s\n' "$ts1" "$ts2" "$(( (ts1-ts2) / (60*60*24) ))" days
    2023-08-23 14:15:05 minus 2023-07-24 19:07:25 is 29 days
    

I think our misunderstanding is how to accomplish step 2.

If you don't want to do it manually, lots of languages have date modules that can do durations: perl, python

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2023-07-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。