0

Is there a way to do time difference with time and not datetime, this is what I would liek to do:

date1 = time.strptime('02/03/2016 16:01:55', '%d/%m/%Y %H:%M:%S')
date2 = time.localtime(time.time())
print date2 - date1

But I am getting only the error:

TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'
Dominik
  • 311
  • 1
  • 4
  • 11
  • So the error is saying that you can't do simple subtraction of time objects. Can you do something like time.difference(date2, date1)? ps I have no python exp. – Mathemats Mar 04 '16 at 01:16
  • Why doesn't `datetime` work for you? – ngoue Mar 04 '16 at 01:23

2 Answers2

0

You can use time.mktime() to get the number of seconds since the epoch from a time_struct:

date = time.strptime('02/03/2016 16:01:55', '%d/%m/%Y %H:%M:%S')
seconds_since_epoch = time.mktime(date)
difference = time.time() - seconds_since_epoch
print time.local_time(difference)
DaveBensonPhillips
  • 3,134
  • 1
  • 20
  • 32
  • What about subtracting two time_struct objects, as the OP asked? – rafaelc Mar 04 '16 at 01:32
  • @RafaelCardoso I don't understand... you can't do that. The OP is asking for the difference between two `time_struct`s, which is exactly what this is – DaveBensonPhillips Mar 04 '16 at 01:44
  • It should be `print time.localtime(difference)` – Dominik Mar 04 '16 at 02:31
  • @Dominik: `time.mktime()` may fail. If you need reliable results; use `pytz`. See related question: [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/q/26313520/4279) – jfs Mar 04 '16 at 23:15
0

Hope this helps

>>> from datetime import datetime
>>>
>>>
>>> d1 = datetime.strptime('02/03/2016 16:01:55', '%d/%m/%Y %H:%M:%S')
>>> d1
datetime.datetime(2016, 3, 2, 16, 1, 55)
>>> d2 = datetime.now()
>>> d1
datetime.datetime(2016, 3, 2, 16, 1, 55)
>>> d2
datetime.datetime(2016, 3, 3, 18, 7, 14, 931872)
>>> d2 - d1
datetime.timedelta(1, 7519, 931872)
>>> (d2 - d1).seconds
7519
>>> (d2 - d1).days
1
rklabzzz
  • 29
  • 1