Python-遥控器主机时区与本地
题
我正在构建用于远程日志监视的网络前端,
我必须管理大约10个不同的地理位置,我已经撞到了三个头的地狱猎犬中。
是否有任何方法可以从远程HPUX SHELL变量获取以下远程信息:
- Zoneinfo(乡村/城市)
- UTC +偏移(我可以轻松地从Zoneinfo获得此功能)
到目前为止,我能得到的最好的是OS缩写的时区(这足以迭代地与静态建造的pytz.common_timezones系列和反向转换为乡村/城市,还是我完全走错了方向? )
获得国家/城市后,我可以轻松获得偏移(我没有)
datetime.now(pytz.timezone('Asia/Dili')).strftime('%Z %z')
'TLT +0900'
- 获取远程缩写时区,
(Linux的理智得多
grep "ZONE=" /etc/sysconfig/clock
输出类似
区域=“欧洲/伦敦”
hp-ux /etc /timezone使用缩写的时区
TZ = CAT-2
我会使用Echo $ tz,它将输出更多有用的数据,例如CAT-2,但某些远程HP-uxes甚至没有配置,从而迫使我依靠模棱两可的RFC822日期,
date +%z
猫
我俩都研究了pytz,datetime.datetime,email.utils,但考虑到没有一个可以直接从缩写时间转换为Zoneinfo Country/City(Pytz允许相反)
我应该只是抓取此Don Quixote的探索,以自动发现远程时区,并在接受注册远程主机的用户输入时添加一个国家/城市下拉列表?
编辑(部分解决方案)
建立@mike Pennington答案
from datetime import datetime as dt
from datetime import timedelta as td
from dateutil.relativedelta import *
from email.Utils import mktime_tz, parsedate_tz
hpux_remote_date = 'Thu Apr 28 18:09:20 TLT 2011'
utctimestamp = mktime_tz(parsedate_tz( hpux_remote_date ))
hpux_dt = dt.fromtimestamp( utctimestamp )
delta_offset = relativedelta(dt.utcnow(), hpux_dt)
hpux_utc = hpux_dt + delta_offset
# Sanity checking to ensure we are correct...
hpux_dt
datetime.datetime(2011, 4, 28, 18, 9, 20)
hpux_utc
datetime.datetime(2011, 4, 28, 9, 9, 22, 229148)
解决方案
您应该能够找到这样的GMT偏移量...
作为GMT偏移,无视DST
(time.localtime()[3] - time.localtime()[8]) - time.gmtime()[3]
我处于中央时间(GMT -6),所以,这产生了 -6
在我的系统上。
作为GMT偏移,包括DST补偿
(time.localtime()[3]) - time.gmtime()[3]
这产生了 -5
在我的系统上。
使用第二种选项可能最容易,并使用它将这些本地HPUX时间转换为GMT。然后与 pytz
按要求。
编辑
如果您正在使用远程(非GMT)时间戳的文本表示形式,则可能更容易与DateTime对象一起工作...我没有HPUX,但是我会假设Date String与我的类似Debian挤压系统。
>>> from datetime import datetime as dt
>>> from datetime import timedelta as td
>>> # using os.popen() to simulate the results of a HPUX shell 'date'...
>>> # substitute the real HPUX shell date string in hpux_date
>>> hpux_date = os.popen('date').read().strip()
>>> hpux_dt = dt.strptime(hpux_date, '%a %b %d %H:%M:%S %Z %Y')
>>> # Rounding to the nearest hour because there *will* be slight delay
>>> # between shell string capture and python processing
>>> offset_seconds = ((dt.utcnow() - hpux_dt).seconds//3600)*3600
>>> hpux_gmt = hpux_dt + td(0,offset_seconds)
>>> # Sanity checking to ensure we are correct...
>>> hpux_gmt
datetime.datetime(2011, 4, 27, 17, 21, 58)
>>> hpux_dt
datetime.datetime(2011, 4, 27, 12, 21, 58)
>>> hpux_date
'Wed Apr 27 12:21:58 CDT 2011'
>>>