Passing a date 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 need to populate a database with pieces of data. I get the data as a flat json string (without nesting), so my work is pretty simple. Ie

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

there is only one problem when the date-time is expressed in the format "YYYY-MM-DDThh: mm: ss + zzzz" (for example, "created" : "2011-11-17T09:21:31+0000" ), which splits the above code.

I know forms.DateTimeField has input_formats . Is there a way to get DateTimeField to accept the format above?

+4
source share
4 answers

Subclass DateTimeField and convert the value accordingly:

 class ConvertingDateTimeField(models.DateTimeField): def get_prep_value(self, value): return str(datetime.strptime(value, FORMAT_STRING)) 

Then use ConvertingDateTimeField to replace models.DateTimeField.

Probably the best way to do this is if you look at how DateTimeField creates a datetime object.

+6
source

You can use ModelForm and override the created form field instead of going directly to your model.

Something like that:

 from django.forms import ModelForm class PostForm(ModelForm): created = forms.DateTimeField(input_formats=('%Y-%m-%dT%H:%M:%S+0000',)) class Meta: model = Post mydict = ... form = PostForm(mydict) if not form.is_valid(): # handle appropriately for your app raise Exception instance = form.save() # or use 'commit=False' if you don't want to save to DB 

Unfortunately, I do not think strptime supports GMT offset, so I hard-coded it into input_format . You can override the "clean" method for this field if you want to clean it yourself.

+2
source

I believe DateTimeField expects a time not a naive datetime, so you need to remove the (+ zzzz) part.

 naive = dt.replace(tzinfo=None) 

Applies only to Python 2.x.

+1
source

ok this is what i did at last:

 class MyDateTimeFeild(models.DateTimeField): def get_prep_value(self, value): from dateutil.parser import parse from datetime import timedelta td = float(value[-5:])/100 timediff = timedelta(hours=td) return parse(value).replace(tzinfo=None) - timediff 

Thanks to everyone! :) all posts were very helpful.

0
source

Source: https://habr.com/ru/post/1381770/


All Articles