This question has been flagged
7 Replies
21905 Views

i want to find the time difference between two time in python. this is my code i got a type error. is this FMT is correct for this datetime?

import time

from datetime import datetime
s1=datetime.now()
print s1
time.sleep(2)
s2=datetime.now()
print s2

FMT = '%Y-%m-%d %H:%M:%s'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print tdelta

 

 

output is:

2014-12-31 17:33:59.692952
2014-12-31 17:34:01.695124
Traceback (most recent call last):
  File "/opt/odoo/trial_projects/check.py", line 14, in <module>
    tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
TypeError: must be string, not datetime.datetime

 

Avatar
Discard
Best Answer

Hello,

when you're trying this:

tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

the s2 and s1 are datetime.datetime objects so you got the error.
you have to change the FMT to :

FMT = '%Y-%m-%d %H:%M:%S.%f'

because .now() return time with msconds ...

then use

tdelta = datetime.strptime(str(d2),FMT) - datetime.strptime(str(d1),FMT)

then you'll get datetime.timedelta object ....

I hope this will help you ...

 

Avatar
Discard
Best Answer

Hai demirel,

     Please specify a header file,

                    from datetime import datetime

     First create a two datetime field in py file,

ex:

                    start_work = fields.Datetime(string="Start work")

                    end_work = fields.Datetime(string="End work")

                    work_hours=fields.Float(string="Total Working Hours",compute='sal_cal',store=True)

then create a compute function name as sal_cal

                    @api.depends('start_work','end_work')

                    def sal_cal(self):

                        t1= datetime.strptime(self.start_work, '%Y-%m-%d %H:%M:%S')

                        t2= datetime.strptime(self.end_work, '%Y-%m-%d %H:%M:%S')

                        s= datetime.strptime(str(t2.time()),'%H:%M:%S') - datetime.strptime(str(t1.time()),'%H:%M:%S')

In this above code is working perfectly to me.please check it now and let me know if any issue are occured


Avatar
Discard

In this above code output is:

2016-06-09 02:30:16

02:30:16

2016-06-09 09:48:43

09:48:43

7:18:27

Best Answer

use this for ref.... surely it will heelp you..

from datetime import datetime
d1='2014-11-15'
d2='2013-11-15'
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
print abs((d2 - d1).days)/(12*30)
print datetime.now().date()

Avatar
Discard

Hi Anand your code show's date alone not the time.

just add like abs((d2 - d1).days)*24

Author Best Answer

i want to find day with time difference...


 

Avatar
Discard

just add like abs((d2 - d1).days)*24