Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing date time in a different format to models.DateTimeField in Django?

I have a model that looks something like this

class Post(models.Model):
    id = models.IntegerField(unique=True, primary_key=True)
    title = models.CharField(max_length=150, blank=True)
    created = models.DateTimeField(blank=True)
    ...

I have to fill the database with chunks of data. I am getting the data in form of a flat json string (no nesting) so my work is pretty easy i.e.

mydict = json.loads(jsonstr)
mypost = Post(**mydict) 
mypost.save()

there is just one issue that the date-time is expressed in "YYYY-MM-DDThh:mm:ss+zzzz" format ( e.g. "created" : "2011-11-17T09:21:31+0000" ) which breaks the above code.

I know forms.DateTimeField has input_formats. Is there a way I could make DateTimeField accept above format?

like image 803
Optimus Avatar asked Dec 27 '22 11:12

Optimus


1 Answers

Subclass DateTimeField and convert the value appropriately:

class ConvertingDateTimeField(models.DateTimeField):

    def get_prep_value(self, value):
        return str(datetime.strptime(value, FORMAT_STRING))

Then use ConvertingDateTimeField to replace models.DateTimeField.

There's probably a better way to do it if you look how DateTimeField creates the datetime object.

like image 63
Chris Lacasse Avatar answered Jan 04 '23 14:01

Chris Lacasse