Get the Olson TZ name for the local timezone?

前端 未结 11 1299
孤街浪徒
孤街浪徒 2020-11-30 03:19

How do I get the Olson timezone name (such as Australia/Sydney) corresponding to the value given by C\'s localtime call?

This is the value overridden vi

11条回答
  •  渐次进展
    2020-11-30 03:31

    This is kind of cheating, I know, but getting from '/etc/localtime' doesn't work for you? Like following:

    >>>  import os
    >>> '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
    'Australia/Sydney'
    

    Hope it helps.

    Edit: I liked @A.H.'s idea, in case '/etc/localtime' isn't a symlink. Translating that into Python:

    #!/usr/bin/env python
    
    from hashlib import sha224
    import os
    
    def get_current_olsonname():
        tzfile = open('/etc/localtime')
        tzfile_digest = sha224(tzfile.read()).hexdigest()
        tzfile.close()
    
        for root, dirs, filenames in os.walk("/usr/share/zoneinfo/"):
            for filename in filenames:
                fullname = os.path.join(root, filename)
                f = open(fullname)
                digest = sha224(f.read()).hexdigest()
                if digest == tzfile_digest:
                    return '/'.join((fullname.split('/'))[-2:])
                f.close()
            return None
    
    if __name__ == '__main__':
        print get_current_olsonname()
    

提交回复
热议问题