Friday, 12 August 2022

How to insert date only from pandas dataframe to postgres

I am trying to insert a pandas dataframe with a date column into a Postgres database such that the data type in Postgres is also a date ('YYYY-MM-DD') but i can only get it to insert at timestamp without a timezone rather than a date. How can I do this?

Here's some starter code (though you'll need postgres creds to connect and test for real):

import pandas as pd
import sqlalchemy

# create toy data
df = pd.DataFrame({'date': ['2022-02-01', '2022-03-11']})
df['date']=df['date'].apply(lambda x: pd.to_datetime(x, format='%Y-%m-%d'))

# connect to postgres
sqlalchemy.create_engine(secrets.get(**SECRETS)))

# insert df into postgres
df.to_sql(
    "toy_table",
    engine,
    schema="toy_schema",
    index=False)



from How to insert date only from pandas dataframe to postgres

No comments:

Post a Comment