[英]execute time period in python
我想通过发送时间段在shell中运行脚本
./test.py 20160830000 201608311100
如何为以下python脚本执行此操作? s
和t
是UNIX时间戳。
#!/usr/bin/python
import requests
from pprint import pprint
import json
import os
import commands
i = commands.getstatusoutput('date -d "2016-08-30" "+%s"')
j = commands.getstatusoutput('date -d "2016-08-31" "+%s"')
s = int(i[1])
t = int(j[1])
url = 'http://192.168.1.96/zabbix/api_jsonrpc.php'
payload = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 0,
"time_from": s,
"time_till": t,
"hostsids": "10105",
"itemids": "23688",
"sortfield": "clock",
"sortorder": "DESC"
},
"auth": "b5f1f71d91146fcc2980e83e8aacd637",
"id": 1
}
header = {
'content-type': 'application/json-rpc',
}
res = requests.post(url, data=json.dumps(payload, indent=True), headers=header)
res = res.json()
pprint(res)
如果我理解正确,那么您想从命令行参数中获取要在jsonrpc调用中使用的时间戳,而不是使用硬编码的日期(出于某种原因,您也使用不赞成使用的commands
模块通过命令行处理date
,而是而不是使用Python的内置time
或datetime
time
模块,后者可以本地处理时间戳和日期)。
这很容易。 Python脚本的命令行参数存储在列表sys.argv
。 列表中的第一个值是脚本的文件名,其余的是参数。 您可能需要检查是否有预期的数量!
尝试这样的事情:
# your other imports here
import sys
USAGE_MSG = "Usage: test.py START_TIMESTAMP END_TIMESTAMP"
if len(sys.argv) != 3:
print(USAGE_MSG)
sys.exit(1)
try:
s = int(sys.argv[1])
t = int(sys.argv[2])
except TypeError: # couldn't convert one of the timestamps to int
print("Invalid timestamp")
print(USAGE_MSG)
sys.exit(1)
# the rest of your code can go here
您可以使用许多其他方式来处理错误检查,在此示例中,我做了一些补充。 当然,您应该使用最适合自己需要的东西。
看一看的时间蟒模块,特别是time.strptime用于解析人类可读串时间到时的结构和功能time.mktime用于转换时间结构为Unix时间戳功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.