【问题标题】:Understanding the returned value of `decode-time` (elisp)了解 `decode-time` 的返回值 (elisp)
【发布时间】:2019-04-07 18:30:24
【问题描述】:

阅读encode-timedecode-time 的文档后,我不明白它们是如何工作的。

我的麻烦来自 encode-time 返回 两个 值,而我只期望一个(自 UNIX 纪元以来的秒数)。这两个值究竟是什么意思?

ELISP> (encode-time 0 0 0 1 1 1970 t)
(0 0)
ELISP> (encode-time 0 0 0 1 1 1971 t)
(481 13184)

我更加困惑,因为这三个调用有效,但我不明白如何解释前两种情况的参数:

;; Ok this is what I expect from the documentation
ELISP> (decode-time
        (encode-time 0 0 0 1 1 1971 t))
(0 0 0 1 1 1971 5 nil 0)

;; This is also what I expected, given it's the same than above, but I don't understand the meaning of the arguments
ELISP> (decode-time '(481 13184))
(0 0 0 1 1 1971 5 nil 0)

;; I kind of understand the following: here 481  is considered the seconds since UNIX epoch,
;; and 13184 is the difference in seconds from UTC.
;; The returned value, is the date (UNIX epoch + 481 seconds)
;; expressed in a timezone 13184 seconds ahead of UTC (45 47 3 1 1 1970 = 13665 seconds
;; and 13665−13184 = 481) 
ELISP> (decode-time 481 13184)
(45 47 3 1 1 1970 4 nil 13184)

请注意,对于上面的所有示例,我都设置了(set-time-zone-rule t) 以避免处理时区。

【问题讨论】:

    标签: elisp


    【解决方案1】:

    (481 131184) 表示秒数为(HIGH LOW),其中HIGH 是高位,LOW 是低16 位。 IE。真正的秒数是

    (+ (* 481 65536) 13184) == 31536000
    

    【讨论】:

      【解决方案2】:

      查看文档:

      (decode-time &optional TIME ZONE)

      将时间值解码为 (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF)。 可选的 TIME 应该是 (HIGH LOW . IGNORED) 的列表, 从'current-time'和'file-attributes'开始,或者使用nil 当前时间。它也可以是单个整数秒数,因为 时代。过时的形式 (HIGH . LOW) 仍然被接受。

      所以我们可以看到预期的格式是一个包含“HIGH”和“LOW”值的列表(可能还有一些额外的信息)。按照这个方向current-time给我们进一步的解释:

      (current-time)

      返回当前时间,作为自 1970-01-01 00:00:00 以来的秒数。 时间以整数列表的形式返回(HIGH LOW USEC PSEC)。 HIGH 具有秒的最高有效位,而 LOW 具有 最低有效 16 位。 USEC 和 PSEC 是微秒和 皮秒计数。

      为什么 Emacs 使用这种看似复杂的格式?毫无疑问,答案很简单,因为 Emacs 已经过时了,它需要在只有 16 位整数可用的系统上工作。

      查看手册,M-x elisp-index-search for current-time 将我们带到(elisp)Time of Day

      这些函数中的大多数将时间表示为四个整数的列表 '(SEC-HIGH SEC-LOW MICROSEC PICOSEC)'。这代表了数量 从“纪元”(1970 年 1 月 1 日 00:00 UTC)开始的秒数,使用 公式:HIGH * 2**16 + LOW + MICRO * 10**−6 + PICO * 10**−12。这 'current-time' 的返回值表示使用这种形式的时间,如 其他函数的返回值中的时间戳,例如 “文件属性”(*注意文件属性的定义::)。在一些 情况下,函数可能返回两个或三个元素的列表,省略 MICROSEC 和 PICOSEC 组件默认为零。

      函数参数,例如,'current-time-string' 的 TIME 参数, 接受更通用的“时间价值”格式,可以是 如上所述的整数,或自纪元以来的秒数,或 当前时间为“无”。您可以将时间值转换为 使用“当前时间字符串”的人类可读字符串和 'format-time-string',使用'seconds-to-time'进入整数列表, 并使用“decode-time”和“float-time”转换成其他形式。这些 功能在以下部分中描述。

      因此,例如,您可以将单个 32 位 Unix 时间戳整数传递给 decode-time

      (decode-time 1554670400)
      => (20 53 8 8 4 2019 1 nil 43200)
      

      也可以使用format-time-string获取单个整数值:

      (string-to-number (format-time-string "%s" (current-time)))
      

      【讨论】:

        猜你喜欢
        • 2013-05-09
        • 2016-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-20
        • 2016-03-02
        • 2019-11-19
        相关资源
        最近更新 更多