Search code examples
pythondjangodatetimedjango-modelsmodel

How to change CSV value into a DateTime object


I am trying to upload data from a CSV into a Django model. On the CSV there is a date field and the values look like this:

2020-11-11 14:06:25+00:00

Which brings up this error:

'“Deadline” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'

I am saving the value into a DateTimeField. How would I convert the CSV data into a DateTime object?

I appreciate your help on this. Thanks!

    class Command(BaseCommand):
        help = 'Upload data from csv'

        def add_arguments(self, parser):
            parser.add_argument("path", type=str)

        def handle(self, *args, **options):
            path = options['path']

            with open(path) as f:
                reader = csv.reader(f, delimiter=';', dialect='excel')
                next(reader)
                for row in reader:

                    job = Project(
                        organization=row[0],
                        category=row[1],
                        project=row[2],
                        description=row[3],
                        deadline=row[4],
                        creation_timestamp=row[5],
                        state=row[6],
                        submitter=row[7],
                        editor=row[8],
                        paid=paid,
                        notes=row[10]
                    )

                job.save()

Solution

  • I'm not 100% sure, cause I don't have much experience with Django, but I believe datetime.datetime.fromisoformat method will do the thing.

    enter image description here

    It gives you datetime object that hopefully can be digested by DateTimeField.