【问题标题】:convert a server timestamp to an epoch in variable将服务器时间戳转换为变量中的纪元
【发布时间】:2021-07-15 05:17:12
【问题描述】:

#!/bin/bash

ctime=date +%s
# returns 1618634997 to $ctime

stime=$(wget --server-response --spider http://www.server.org/news_32.mp3 2>&1 | grep -i Last-Modified)

# returns : Last-Modified: Sat, 17 Apr 2021 04:49:57 GMT # into the variable $stime

我需要将$stime转换为纪元时间,放入$etime进行比较,然后决定是否下载文件。

需要一些代码来操作字符串。

做日期比较

diff=$(( (ctime - eftime) / 86400 ))
echo $diff

以天为单位返回差异。

我的解决方案,经过多次尝试分解原始字符串后发现

stime=$(wget --server-response --spider http://server.org.au/local.mp3 2>&1 | grep -i Last-Modified)

a=$stime

a=${a/*,/} ; a=${a/\ GMT/} ; dmt=${a/2021 /} ; dm=${a/2021*/} ; tm=${dmt/????????/} ; dd=${dm%?????*} ; mmm=${dm#*????}

fst="${mmm}${dd} ${tm}"

epoch=$(date -d "${fst}" +"%s")

echo "server file time = $fst"

ftime=$epoch

ctime=date +%s``

diff=$(( (ctime - ftime) / 86400 ))

echo "age "$diff" days"

exit

很尴尬,我知道 :) 感谢您的回答,对这个网站非常陌生,现在尝试简单的方法。

【问题讨论】:

  • 如果您使用的是 GNU coreutils,您可以使用 date(1) 的 -d 选项,但这可能会给您的用例带来可移植性问题。这是你的选择吗?
  • 如果没有,Perl 在其标准库中有一个人类可读的日期解析器; stackoverflow.com/questions/7357423/…

标签: bash


【解决方案1】:

尝试以下方法:

 eftime=$(date -d "$(wget --server-response --spider http://www.server.org/news_32.mp3 2>&1 | awk -F: '/Last-Modified/ { print $2 }')" +%s)
 diff=$(( (ctime - eftime) / 86400 ))
 echo $diff

解释:

 wget --server-response --spider http://www.server.org/news_32.mp3 2>&1 | awk -F: '/Last-Modified/ { print $2 }'

获取 wget 的输出,然后搜索带有“Last-Modified”的行并打印第二个“:”分隔字段。将其用作日期描述符并使用 +%s 以纪元格式打印。

【讨论】:

  • 比我最终得到相同结果的方式好多了,谢谢
【解决方案2】:

您可以同时使用日期。
获取纪元秒并将其转换回正常日期...

date --date="@$(date +%s)"

如果你喜欢 Lua,那么你可以...

-- get epoch seconds
>os.time()
1619002966
-- Convert it to a date
>os.date(_,os.time())
Wed Apr 21 13:03:11 2021

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2021-01-18
    • 1970-01-01
    • 2018-08-03
    相关资源
    最近更新 更多