简体   繁体   中英

How to get the correct time difference in seconds in Python?

I am writing a python script to check the time on a remote system using SNMP. I have used the modules subprocess, pytz, datetime and time in this script.

The problem is when I take the time difference using this script, it is not getting me the correct time difference in seconds. Can anyone help me with this?

# Finding remote time
snmp_remote_ts = subprocess.run(["/usr/bin/snmpwalk", "-r", "3", "-c", "{}".format(snmp_community), "-v", "{}".format(snmp_ver), "{}:{}".format(remote_host,snmp_port), "{}".format(OID_hrSystemDate)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
remote_time = snmp_remote_ts.stdout.decode().split()[-1].replace(","," ").split(".")[0]
remote_ts = int(time.mktime(datetime.datetime.strptime(remote_time, "%Y-%m-%d %H:%M:%S").timetuple()))

# Finding actual time of provided timezone
actual_time_now = int(datetime.datetime.now(timezone(remote_tz)).timestamp())

# Finding time difference
time_diff = actual_time_now - remote_ts

I have solved the issue by rewriting the code as per below:

# Finding remote time
snmp_remote_ts = subprocess.run(["/usr/bin/snmpwalk", "-r", "3", "-c", "{}".format(snmp_community), "-v", "{}".format(snmp_ver), "{}:{}".format(remote_host,snmp_port), "{}".format(OID_hrSystemDate)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
remote_time = snmp_remote_ts.stdout.decode().split()[-1].replace(","," ").split(".")[0]
remote_ts = datetime.datetime.strptime(remote_time, "%Y-%m-%d %H:%M:%S")

# Finding actual time of provided timezone
actual_time_now = datetime.datetime.now(timezone(remote_tz)).replace(tzinfo=None,microsecond=0)

# Finding time difference
time_diff = actual_time_now - remote_ts
time_diff_seconds = time_diff.seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM