How can I get a human-readable timezone name in Python?

前端 未结 7 1403
旧时难觅i
旧时难觅i 2020-12-10 12:06

In a Python project I\'m working on, I\'d like to be able to get a \"human-readable\" timezone name of the form America/New_York, corresponding to the syste

7条回答
  •  爱一瞬间的悲伤
    2020-12-10 12:56

    If you want only literally what you asked for, "the timezone name of the form America/New_York, corresponding to the system local timezone", and if you only care about Linux (and similar), then this should do the job:

    import os
    import os.path
    import sys 
    
    def main(argv):
      tzname = os.environ.get('TZ')
      if tzname:
        print tzname
      elif os.path.exists('/etc/timezone'):
        print file('/etc/timezone').read()
      else:
        sys.exit(1)
    
    if __name__ == '__main__':
      main(sys.argv)
    

    Of course it would be nicer to have a library that encapsulates this in a cleaner way, and that perhaps handles the other cases you mention in comments like already having a tzinfo object. I think you can do that with pytz mentioned by Amber but it's not obvious to me just how...

提交回复
热议问题