使用Pandas上传CSV至PostgreSQL失败,如何修复该问题?
问题原因
你的报错核心是store_status表的timestamp_utc字段存在两种时间格式:
- 带毫秒的格式(如
2023-01-25 05:01:37.123) - 不带毫秒的格式(如
2023-01-25 05:01:37)
但你在调用pd.to_datetime时指定了固定格式%Y-%m-%d %H:%M:%S.%f,这个格式强制要求必须包含毫秒部分(.%f),导致不带毫秒的时间字符串匹配失败。
修复方案
有两种简单有效的修复方式:
方案1:让Pandas自动推断时间格式(推荐)
使用format='mixed'参数,让Pandas自动识别每条记录的时间格式,兼容带/不带毫秒的情况:
store_status['timestamp_utc'] = pd.to_datetime(store_status['timestamp_utc'], format='mixed', utc=True)
方案2:统一补全毫秒后再解析
如果需要严格遵循指定格式,可以先给不带毫秒的时间字符串补全.000,再用原格式解析:
# 补全毫秒部分 store_status['timestamp_utc'] = store_status['timestamp_utc'].apply( lambda x: x + '.000' if len(x.split(' ')[1]) == 8 else x ) # 按原格式解析 store_status['timestamp_utc'] = pd.to_datetime(store_status['timestamp_utc'], format='%Y-%m-%d %H:%M:%S.%f', utc=True)
修改后的完整脚本
from sqlalchemy import create_engine import pandas as pd # Define the PostgreSQL connection URL DB_USERNAME = 'postgres' DB_PASSWORD = '1234' DB_HOST = 'localhost' DB_PORT = '5432' DB_NAME = 'store' POSTGRES_URL = f'postgresql://{DB_USERNAME}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}' engine = create_engine(POSTGRES_URL) # Load the CSV files store_timezones = pd.read_csv('bq-results-20230125-202210-1674678181880.csv', dtype={'store_id': 'int64'}) menu_hours = pd.read_csv('Menu_hours.csv', dtype={'store_id': 'int64', 'day': 'int8'}) store_status = pd.read_csv('store_status.csv', dtype={'store_id': 'int64'}) # Preprocess the 'timestamp_utc' column to remove 'UTC' part store_status['timestamp_utc'] = store_status['timestamp_utc'].str.replace(' UTC', '') # Parse datetime strings in 'store_status'(使用方案1的修复) store_status['timestamp_utc'] = pd.to_datetime(store_status['timestamp_utc'], format='mixed', utc=True) menu_hours['start_time_local'] = pd.to_datetime(menu_hours['start_time_local'], format='%H:%M:%S').dt.time menu_hours['end_time_local'] = pd.to_datetime(menu_hours['end_time_local'], format='%H:%M:%S').dt.time # Import data into the database store_timezones.to_sql('store_timezones', engine, if_exists='append', index=False) menu_hours.to_sql('menu_hours', engine, if_exists='append', index=False) store_status.to_sql('store_status', engine, if_exists='append', index=False) print('Data imported successfully')
内容的提问来源于stack exchange,提问作者Rahul Nakum
相关产品推荐
相关产品推荐

