Import csv with dates

Hello!!

I’m trying to import a local csv file using uplink. I have no problems with text and number types. But I can’t figure how to import date columns.

What I have is:

  1. A datatable named “datetable” with one column named “datetime” of type date.
    image

  2. A csv with one column and one row:
    image

  3. This local python code (the same as the one in the docs). It’s working for other types.
    image

What I have tried for a couple of hours, and not worked:

  1. Try to match the date format in two ways (yyyy-mm-dd ; dd-mm-yyyy)
  2. I try with date(yyyy,mm,dd) instead of yyy-mm-dd.
  3. Finally I exported the datatable and imported it again (after removing the ID column). I thougth that in this case the types will match exactly the date format of Anvil. But still nothing.

I’ve always get the same error:
anvil.tables._errors.TableError: “Column ‘datetime’ is a date - cannot set it to a string”

I also search the forum. But I can’t find anything.

please anyone help.

thanks,
Edmundo

You have to manually convert the datetime column in your csv to a datetime object before adding the row to the table. The table does not automatically convert strings to datetimes.

def import_csv_data(file):
    with open(file,"r") as r:
        df = pd.read_csv(f)
        for d in df.to_dict(orient="records"):
            d['datetime'] = datetime.strptime(d['datetime'],"%Y-%m-%d")
            app_tables.datatable.add_row(**d)

This isn’t test, off the fly so you might need to run on a single row and debug a bit.

Hope this helps!

1 Like

I made this clonable example, if you look at the code in it, how to parse datetimes is there.
Or you can just use it to load your data.

Also welcome to anvil! :wave:

Thanks!!! It worked!
I just had to make a small change. I need to convert datetime to date by adding the date() method.
amazing!
thanks again

1 Like