问题原文
原帖链接 · 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:
you have timestamp one:
ts1=$( date -d "08/23/2023 14:15:05" "+%s" )you get a second timestamp, however you want
ts2=$( date -d "now - 15 minutes" "+%s" )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
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
