2

I have some problems with format from string to int in Python:

obj=self.browse(cr,uid,ids,context=context)[0]
hour_den=obj.time_in[12:13]
hour_di=obj.time_out[12:13]
min_den=obj.time_in[15:16]
min_di=obj.time_out[15:16]
gl=hour_di-hour_den
pl=min_di-min_den

and error is:

 unsupported operand type(s) for -: 'unicode' and 'unicode'

how can i format it ?? Help me please! Thanks!!!

4 Answers 4

1

It is not clear what type obj is. However you could do.

obj=self.browse(cr,uid,ids,context=context)[0]
hour_den = hour_di = min_den = min_di = 0
try:
  hour_den=int(obj.time_in[12:13])
  hour_di=int(obj.time_out[12:13])
  min_den=int(obj.time_in[15:16])
  min_di=int(obj.time_out[15:16])
except ValueError:
  return False
gl=hour_di-hour_den
pl=min_di-min_den

But better do casting to int in separete function

I suspect you indexes are incorrect. If you need to manually parse date in fixed format like "2011-12-14 02:20:11". You could use following:

ts = "2011-12-14 02:20:11"
date, time = ts.split()
hours, mins, secs = time.split(':')
try:
  hours=int(hours)
  mins=int(mins)
  secs=int(secs)
except ValueError:
  return False
Sign up to request clarification or add additional context in comments.

2 Comments

error again is ValueError: invalid literal for int() with base 10: '' i do abot the hour and minues with obj.time_in is "2011-12-14 02:20:11" and i want cut minues and hour of it and convert to int. for do some calculation
This answer has one thing I've been told is the "Python" way of doing things. That is using try except. It was even explained to me I should look for non-numerics in our water account data by assigning the value of a numeric account # column to an integer in a try .. except block, instead of using an if statement.
0

Utilize strptime from datetime:

from datetime import datetime
hour_den = '12:13'
hour_di = '12:15'
FMT = '%H:%M'
timedelta = datetime.strptime(hour_di, FMT) - datetime.strptime(hour_den, FMT)
print timedelta

Comments

0

If these are integers, you can use "int" to convert to an integer. For example:

hour_den=int(obj.time_in[12:13])

Comments

0
gl = int(hour_di) - int(hour_den)
pl = int(min_dl) - int(min_den)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.