簡體   English   中英

在python中執行時間段

[英]execute time period in python

我想通過發送時間段在shell中運行腳本

./test.py 20160830000 201608311100

如何為以下python腳本執行此操作? st是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的內置timedatetime 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM