Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

‘“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 the thing.

enter image description here

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading