For example, I have an input from a csv which is 08:00:00 so this is in string type. and I have a timefield in the model. I need to insert that string in the timefield. Is there an efficient way of converting this and inserting it into a timefield? I know something but it's kinda like a long way.
You can convert it by using the datetime
module of python
from datetime import datetime
t = '08:00:00'
t = datetime.strptime(t, '%H:%M:%S')
print t, type(t)
>>> 1900-01-01 08:00:00 <type 'datetime.datetime'>
Note the year, month, day will start from 1900-01-01
because there is no date information available in the string.
TimeField will accept a datetime.time instance. Therefore, what you need is providing a time object for it
import datetime
a = YourModel()
a.YourTimeField = datetime.datetime.strptime('12:12:12', '%H:%M:%S').time()
a.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With