Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
7 Trả lời
24628 Lượt xem

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

 

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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 ...

 

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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


Ảnh đại diện
Huỷ bỏ

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

Câu trả lời hay nhất

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()

Ảnh đại diện
Huỷ bỏ

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

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

Tác giả Câu trả lời hay nhất

i want to find day with time difference...


 

Ảnh đại diện
Huỷ bỏ

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

Bài viết liên quan Trả lời Lượt xem Hoạt động
3
thg 10 23
5907
2
thg 1 23
5298
11
thg 9 19
38413
0
thg 5 16
3896
0
thg 4 16
4191