Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way of converting time string and inserting it to a time field django

Tags:

python

django

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.

like image 348
Leonid Avatar asked Dec 16 '22 14:12

Leonid


2 Answers

You can convert it by using the datetimemodule 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.

like image 116
Aamir Rind Avatar answered Dec 21 '22 09:12

Aamir Rind


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() 
like image 31
Thai Tran Avatar answered Dec 21 '22 11:12

Thai Tran