0
time  = datetime.strptime(str(shift_change_ob.shift_date) ,"%Y-%m-%d %H:%M:%S").strftime("%H:%M")
self.orginal_shift_time = float(time)

type(time) is string while type(self.orginal_shift_time) is float. So I am getting ValueError: invalid literal for float(): 07:00. How can I assign string value to float field?

4
  • 07:00 should be converted to what float? Commented May 9, 2017 at 5:24
  • "print time" prints 07:00. But type(time) is string. I want to assign it to a field whose type is float. Commented May 9, 2017 at 5:27
  • 07:00 is not assignable to float. Floats are of the form "int.int" Commented May 9, 2017 at 5:29
  • you want 07:30 in float like 7.5 right? which means 7 an half hour! Commented May 9, 2017 at 5:54

2 Answers 2

1

Sine you were using colon strftime("%H:%M") to seperate hours and minutes, it is not possible to convert to float.

So replace colon with dot strftime("%H.%M"), now it will works.

>>> time = strftime("%H.%M")
>>> shift_time = float(time)
>>> shift_time
10.55
Sign up to request clarification or add additional context in comments.

1 Comment

oh! Thnku :) That was a silly mistake that I had done!
0

The time variable will have string, If you want hour and minute.. use datetime.hour and datetime.minute. I am assuming shift_change_ob.shift_date is a datetime object. you can get the value from this object itself.

shift_change_ob.shift_date.hour
shift_change_ob.shift_date.minute 

should give what you want.

If you need to store the value as a single float variable you can,

time  = datetime.strptime(str(shift_change_ob.shift_date) ,"%Y-%m-%d %H:%M:%S").strftime("%H:%M")
f_time = float(time.split(':')[0] + '.' + str(float(time.strip(':')[1])*(10/6)))

10/6 is the factor to convert minutes into decimal.

1 Comment

Thank You! :) Didnt know about the 10/6 factor

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.