1

I am trying insert data in a DATE format at database using SqlAlchemy, the problem is when I go check the database, there are only NULL values.

How to Insert Timestamp data into MySQL db using python/SqlAlchemy.

AttributeError: 'Timestamp' object has no attribute 'translate'.

Data


import numpy as np
import pandas as pd

import sqlalchemy as db
from sqlalchemy import create_engine
import pymysql
import MySQLdb

import json
import datetime
import time


# dataframe
df = pd.DataFrame({ "year" : [ "2017/10/10", "2018/10/10", "2019/10/10"]


my code:

# transforming to datetime
df.year = pd.to_datetime(df.year)

out[]: 
year   datetime64[ns]



#adding in list of dict to be able to insert at db

values_list2 = []   
for i in range(len(df)):
    values_list2.append({ "Rece_Year": df["year"][i] })



# create table in db with Datetime column format

data = db.Table('Test', metadata,                
              db.Column('Rece_Year',  db.DateTime(), default=True),                                      
              extend_existing=True 
              )


metadata.create_all(engine)

#Insert data
query = db.insert(data) 


If I use String, it works. but I need in a DATE format

data = db.Table('Test', metadata,                 
              db.Column('Rece_Year',  db.String(100), nullable=True),                                      
              extend_existing=True 
              )


metadata.create_all(engine)

4
  • 2
    Have you tried pandas native function DataFrame.to_sql? Commented Jan 14, 2020 at 0:12
  • @Erfan nop, let me try this.. Commented Jan 14, 2020 at 0:15
  • @Parfait, I updated the question ``` db = SqlAlchemy``` as you can check at the import Commented Jan 14, 2020 at 18:03
  • 1
    Please show output of SHOW CREATE TABLE Test so we can see your table schema. Also what is metadata? Please set up minimal reproducible example. Commented Jan 14, 2020 at 18:27

1 Answer 1

1

So I changed the Data type in the db itself, and it worked. So it seems it was a issue with SqlAlchemy packaging, not sure.

So it is not really an answer, but that is what I got to work unfortunately.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.