Python日期时间与None值比较(Landscape API)

1 投票
1 回答
2192 浏览
提问于 2025-04-17 16:23

我正在从一个网络服务中提取一些数据,其中一个参数是 last_ping_time,这个值有时候可能是 None。为了检查与机器的通信,我需要把当前日期和 last_ping_time 进行比较。

结果我遇到了一个错误:

ValueError: time data 'None' does not match format '%Y-%m-%dT%H:%M:%SZ'

我尝试在获取到 None 的时候设置一个虚拟值。

   if ping=="None":

   ping="2013-01-01T00:00:00

我还试过使用 break 或 continue,但似乎没有效果,这个错误依然存在。我需要在遇到 null 的时候继续循环到下一个值,或者设置一个虚拟值然后继续处理。

with open(filename, 'wb') as csvfile:   #Creating report file
    spamwriter = csv.writer(csvfile, delimiter='    ')
    for computer in computers:

        ping=computer["last_ping_time"]
        ping=str(ping)
        ping.split('T')
        if ping=="None":
        #break
        ping="2013-01-01T00:00:00"  
        else

                ping=datetime.datetime.strptime(ping, '%Y-%m-%dT%H:%M:%SZ') # Convert string to data

                if ping<Current_Date: 
                        #toremove=count+1
                        os.system('zenity --info --text="Computers not contacting more than 30 days:%s "' % (computer["hostname"]))
                        #print "Needs to be deleted" #Control Variable

                        spamwriter.writerow((computer["id"], computer["hostname"], computer["title"], computer["last_ping_time"], "30 Days from last contact machine will be be removed"))
                else:
                        network=str(computer) #list to string
                        ip=network.split("u'ip_address': u'")[1] #1 shows what is after parameters
                        ip=ip.split("'")[0] #0 shows what is before parameters
                        mac=network.split("u'mac_address': u'")[1]
                        mac=mac.split("'")[0] 
                        print mac
                        print ip
                        spamwriter.writerow((computer["id"], computer["hostname"], computer["title"], computer["last_ping_time"], mac, ip)) 
os.system('zenity --info --text="Report is created with name:%s "' % (filename))

1 个回答

0

ping = str(ping) 这一行去掉,然后使用下面的代码:

if ping is None:
   # no last ping time

撰写回答