[Django]-Upload any DateTime from CSV in Django

2👍

From what I can see, DATETIME_INPUT_FORMATS is being used in django forms only. It will validate any date given in formats with DATETIME_INPUT_FORMATS. But when you are using the model directly to store the data, it will only accept data if its given in YYYY-MM-DD HH:MM. It evaluates the datetime string against this regex. So I would recommend to write a custom manager to convert the values to datetime format, and use it to create/update the value. For example:

from django.utils import formats


class CustomManager(models.Manager):
    def custom_update_or_create(self,*args, **kwargs):
        date_time_value = kwargs.pop('date', None)
        if date_time_value:
            kwargs['date'] = self.get_date_value(date_time_value)
        return super(CustomManager, self).update_or_create(*args, **kwargs)

    def get_date_value(self, value):
         input_formats = [
            '%d-%m-%y %H:%M',
            '%d-%y-%m %H:%M',
            '%m-%d-%y %H:%M',
            '%m-%y-%d %H:%M',
            '%y-%m-%d %H:%M',
            '%y-%d-%m %H:%M',
            '%d/%m/%y %H:%M',
            '%d/%y/%m %H:%M',
            '%m/%d/%y %H:%M',
            '%m/%y/%d %H:%M',
            '%y/%m/%d %H:%M',
            '%y/%d/%m %H:%M'
         ]

         for format in input_formats:
            try:
                return self.strptime(value, format)
            except (ValueError, TypeError):
                continue

    def strptime(self, value, format):
        return datetime.datetime.strptime(value, format)

And Use it in the model:

class ItemBatch(models.Model):
    date = models.DateTimeField(blank=True, null=True, default=datetime.date.today)
    # rest of the fields
    objects = CustomManager()

Finally use that method to create/update new instances:

ItemBatch.objects.custom_update_or_create(name=column[0], pid=column[1], quantity=column[2],date=column[8])
👤ruddra

0👍

You will need to add following in settings.py:

DATETIME_INPUT_FORMATS = [
'%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
'%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
'%Y-%m-%d',              # '2006-10-25'
'%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
'%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
'%m/%d/%Y',              # '10/25/2006'
'%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
'%m/%d/%y %H:%M',        # '10/25/06 14:30'
'%m/%d/%y',              # '10/25/06'
]
👤kamran

Leave a comment