Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
1
Indexable
Never
from datetime import datetime

# Replace 'None' and 'NaT' with None in source_row
for column_name, source_val in source_row.items():
    if source_val == 'None' or source_val == 'NaT':
        source_row[column_name] = None
    elif isinstance(source_val, str) and ' ' in source_val:
        try:
            source_row[column_name] = datetime.strptime(source_val, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass  # Handle invalid datetime strings here

# Generate an INSERT query dynamically
insert_query = f"INSERT INTO {schema_ext}.{table_name} ("
insert_columns = []
insert_values = []

for column_name, source_val in source_row.items():
    if source_val is not None:
        if isinstance(source_val, datetime):
            # Format the datetime as needed for your database, e.g., 'YYYY-MM-DD HH:MM:SS'
            formatted_datetime = source_val.strftime('%Y-%m-%d %H:%M:%S')
            insert_values.append(f"'{formatted_datetime}'")
        else:
            insert_values.append(f"'{source_val}'")
    else:
        insert_values.append('NULL')

insert_query += ", ".join(insert_columns)
insert_query += ") VALUES ("
insert_query += ", ".join(insert_values)
insert_query += ")"