从tzdata中提取历史性的闰秒

Bas*_*els 20 python datetime astronomy tzinfo leap-second

有没有办法从大多数Linux发行版上分发的时区数据库中提取历史性闰秒的时刻?我在python中寻找一个解决方案,但在命令行上运行的任何东西都可以.

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

我有工作函数在gps-time和UTC之间转换,但我不得不硬编码闰秒表,我在这里(文件tzdata2013xx.tar.gz包含一个名为的文件leapseconds).每隔几年宣布新的leapsecond时,我必须手动更新此文件.我更希望从标准的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)
Run Code Online (Sandbox Code Playgroud)

结果

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
Run Code Online (Sandbox Code Playgroud)

虽然这确实解决了我的问题,但我可能不会采用这种解决方案.相反,我将使用我的代码包含leap-seconds.list,如Matt Johnson所建议的那样.这似乎是用作tzdata源的权威列表,可能每年两次由NIST更新.这意味着我将不得不手动进行更新,但是这个文件很容易解析并包含一个到期日期(tzdata似乎缺失了).

ste*_*eha 10

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

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

编辑:程序更新到现在是正确的.它现在使用该文件/usr/share/zoneinfo/right/UTC,现在它可以找到打印的闰秒.

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

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)
Run Code Online (Sandbox Code Playgroud)