python - 从 tzdata 中提取历史闰秒

标签 python datetime astronomy tzinfo leap-second

有没有办法从分布在大多数 linux 发行版上的时区数据库中提取历史闰秒时刻?我正在寻找 python 中的解决方案,但是任何在命令行上工作的东西都可以。

我的用例是在 GPS 时间(基本上是自 1980 年第一颗 GPS 卫星开启以来的秒数)和 UTC 或本地时间之间进行转换。 UTC 不时调整闰秒,而 gps-time 线性增加。这相当于在 UTC 和 TAI 之间进行转换。 . TAI 也忽略闰秒,因此 TAI 和 gps-time 应该始终以相同的偏移量演变。在工作中,我们使用 gps-time 作为同步世界各地天文观测的时间标准。

我有在 gps-time 和 UTC 之间转换的工作函数,但我必须硬编码一个闰秒表,我得到 here (文件 tzdata2013xx.tar.gz 包含一个名为 leapseconds 的文件)。每隔几年,当宣布新的闰秒时,我必须手动更新此文件。我更愿意从标准 tzdata 中获取这些信息,该信息每年会通过系统更新数次自动更新。

我很确定这些信息隐藏在 /usr/share/zoneinfo/ 的某些二进制文件中。我已经能够使用 struct.unpack 提取其中的一些(man tzfile 提供了一些有关格式的信息),但我从来没有让它完全工作。是否有任何标准软件包可以访问此信息?我知道pytz ,它似乎从同一个数据库中获取标准 DST 信息,但它不提供对闰秒的访问。我还找到了tai64n ,但是查看它的源代码,它只包含一个硬编码的表格。

编辑

灵感来自 steveha 的回答和 pytz/tzfile.py 中的一些代码,我终于得到了一个可行的解决方案(在py2.5和py2.7上测试过):

from struct import unpack, calcsize
from datetime import datetime

def print_leap(tzfile = '/usr/share/zoneinfo/right/UTC'):
    with open(tzfile, 'rb') as f:
        # read header
        fmt = '>4s c 15x 6l'
        (magic, format, ttisgmtcnt, ttisstdcnt,leapcnt, timecnt,
            typecnt, charcnt) =  unpack(fmt, f.read(calcsize(fmt)))
        assert magic == 'TZif'.encode('US-ASCII'), 'Not a timezone file'
        print 'Found %i leapseconds:' % leapcnt

        # skip over some uninteresting data
        fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict(
            timecnt=timecnt, ttinfo='lBB'*typecnt, charcnt=charcnt)
        f.read(calcsize(fmt))

        #read leap-seconds
        fmt = '>2l'
        for i in xrange(leapcnt):
            tleap, nleap = unpack(fmt, f.read(calcsize(fmt)))
            print datetime.utcfromtimestamp(tleap-nleap+1)

结果

In [2]: print_leap()
Found 25 leapseconds:
1972-07-01 00:00:00
1973-01-01 00:00:00
1974-01-01 00:00:00
...
2006-01-01 00:00:00
2009-01-01 00:00:00
2012-07-01 00:00:00

虽然这确实解决了我的问题,但我可能不会选择这个解决方案。相反,我将包括 leap-seconds.list按照马特约翰逊的建议,使用我的代码。这似乎是用作 tzdata 来源的权威列表,并且可能每年由 NIST 更新两次。这意味着我将不得不手动进行更新,但是这个文件很容易解析并且包含一个到期日期(似乎缺少 tzdata)。

最佳答案

我刚刚做了 man 5 tzfile 并计算了一个可以找到闰秒信息的偏移量,然后读取闰秒信息。

您可以取消注释“DEBUG:”打印语句以查看它在文件中找到的更多内容。

编辑:程序更新为现在正确。它现在使用文件 /usr/share/zoneinfo/right/UTC 并找到闰秒来打印。

原始程序没有跳过 timezeone 缩写字符,这些字符记录在手册页中,但有点隐藏(“......并且 tt_abbrind 用作遵循 ttinfo 结构的时区缩写字符数组的索引( s) 在文件中。")。

import datetime
import struct

TZFILE_MAGIC = 'TZif'.encode('US-ASCII')

def leap_seconds(f):
    """
    Return a list of tuples of this format: (timestamp, number_of_seconds)
        timestamp: a 32-bit timestamp, seconds since the UNIX epoch
        number_of_seconds: how many leap-seconds occur at timestamp

    """
    fmt = ">4s c 15x 6l"
    size = struct.calcsize(fmt)
    (tzfile_magic, tzfile_format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt,
        typecnt, charcnt) =  struct.unpack(fmt, f.read(size))
    #print("DEBUG: tzfile_magic: {} tzfile_format: {} ttisgmtcnt: {} ttisstdcnt: {} leapcnt: {} timecnt: {} typecnt: {} charcnt: {}".format(tzfile_magic, tzfile_format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt))

    # Make sure it is a tzfile(5) file
    assert tzfile_magic == TZFILE_MAGIC, (
            "Not a tzfile; file magic was: '{}'".format(tzfile_magic))

    # comments below show struct codes such as "l" for 32-bit long integer
    offset = (timecnt*4  # transition times, each "l"
        + timecnt*1  # indices tying transition time to ttinfo values, each "B"
        + typecnt*6  # ttinfo structs, each stored as "lBB"
        + charcnt*1)  # timezone abbreviation chars, each "c"

    f.seek(offset, 1) # seek offset bytes from current position

    fmt = '>{}l'.format(leapcnt*2)
    #print("DEBUG: leapcnt: {}  fmt: '{}'".format(leapcnt, fmt))
    size = struct.calcsize(fmt)
    data = struct.unpack(fmt, f.read(size))

    lst = [(data[i], data[i+1]) for i in range(0, len(data), 2)]
    assert all(lst[i][0] < lst[i+1][0] for i in range(len(lst)-1))
    assert all(lst[i][1] == lst[i+1][1]-1 for i in range(len(lst)-1))

    return lst

def print_leaps(leap_lst):
    # leap_lst is tuples: (timestamp, num_leap_seconds)
    for ts, num_secs in leap_lst:
        print(datetime.datetime.utcfromtimestamp(ts - num_secs+1))

if __name__ == '__main__':
    import os
    zoneinfo_fname = '/usr/share/zoneinfo/right/UTC'
    with open(zoneinfo_fname, 'rb') as f:
        leap_lst = leap_seconds(f)
    print_leaps(leap_lst)

关于python - 从 tzdata 中提取历史闰秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332902/

相关文章:

python - 使用正则表达式过滤列表

python - 如何根据元素转换成本排序对集合进行排序,以使连续集合之间的更改最小化?

命令中的 python 变量与 os.system 一起执行

java - SimpleDateFormat 结果不正确

c# - 只是日期或时间

c# - 如何计算圆绕球体的曲率(弧)?

python - 使用适用于 Python 的 Box.com SDK

php - DB2 时间戳 PHP 日期时间

algorithm - 哪些算法可以让我模拟行星物理?

python - AstroPy距离红移转换精度