1
for proc in psutil.process_iter():
     if proc.name == "monit":
         current_time = time.localtime()
         proc_start_time = time.localtime(proc.create_time)
         print (current_time - proc_start_time).seconds

I am not able to find difference between two datetimes. Can't subtract them give Error -
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'

script_kiddie
  • 1,167
  • 4
  • 12
  • 24

1 Answers1

4

current_time and proc_start_time are strings because that is what strftime returns.

You'll want to get rid of current_time, and make proc_start_time = time.localtime(proc.create_time). Now you have two time objects, which will allow you to find the difference.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • I made two times as objs of same type - current_time = time.localtime(); proc_start_time = time.localtime(proc.create_time); print (current_time - proc_start_time).seconds .Still gives error TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time' – script_kiddie Sep 15 '13 at 23:35
  • @script_kiddie I've never worked with those type of objects, but I have worked with datetime objects. If you convert those using [this method](http://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object), you should be able to. Sorry I couldn't give a better answer – TerryA Sep 15 '13 at 23:37
  • dt = datetime.fromtimestamp(mktime(proc_start_time)) AttributeError: 'module' object has no attribute 'fromtimestamp' , where proc_start_time is time.struct_time object – script_kiddie Sep 15 '13 at 23:49
  • @script_kiddie If you did `import datetime`, then you need to put `datetime.datetime` at the beginning – TerryA Sep 15 '13 at 23:51
  • :current_time = datetime.datetime.today(); proc_start_time = time.localtime(proc.create_time); dt = datetime.datetime.fromtimestamp(mktime(proc_start_time)); print (current_time - dt).seconds gives me 13736 while print (current_time - dt).days gives me 39 .. how come this mismatch ? – script_kiddie Sep 15 '13 at 23:58
  • @script_kiddie I'm sorry, I have no idea. – TerryA Sep 16 '13 at 00:06