You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含UTC的Pandas字符串列转为BigQuery TIMESTAMP并加载

解决带UTC后缀的时间字符串加载到BigQuery TIMESTAMP列的问题

你遇到的object of type <class 'str'> cannot be converted to int错误,本质是BigQuery无法直接解析带UTC后缀的字符串为TIMESTAMP类型,默认会尝试把字符串转成时间戳整数,自然失败。核心解决思路是先把CSV中的时间字符串转换成Pandas的带UTC时区的datetime对象,再加载到BigQuery。

1. 正确读取CSV并解析时间列

读取CSV时需要自定义解析逻辑处理带UTC后缀的时间格式,以下两种方法都可行:

方法一:移除UTC后缀后解析

import pandas as pd

# 读取CSV后,先移除t_time列的" UTC"后缀,再转换为带UTC时区的datetime
df = pd.read_csv("your_data.csv")
df["t_time"] = pd.to_datetime(df["t_time"].str.replace(" UTC", ""), utc=True)

方法二:用格式字符串精准匹配解析

直接通过datetime的格式规则匹配带UTC后缀的时间字符串:

from datetime import datetime
import pandas as pd

def parse_utc_time(time_str):
    # 匹配"2023-01-01 07:20:54.272000 UTC"格式
    return datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f UTC").replace(tzinfo=datetime.timezone.utc)

# 读取时直接指定解析列和解析函数
df = pd.read_csv("your_data.csv", parse_dates=["t_time"], date_parser=parse_utc_time)

2. 加载到BigQuery的正确配置

确保加载时指定对应schema,同时保证datetime列格式被正确识别:

用pandas_gbq加载示例

from google.cloud import bigquery
import pandas_gbq

# 定义与目标表一致的schema
schema = [
    bigquery.SchemaField("t_time", "TIMESTAMP", mode="NULLABLE"),
    # 其他列的schema定义...
]

# 执行加载,指定api_method为load_csv更稳定处理时间类型
pandas_gbq.to_gbq(
    dataframe=df,
    destination_table="你的项目ID.数据集ID.表名",
    project_id="你的项目ID",
    schema=schema,
    if_exists="append",  # 按需选append/replace等
    api_method="load_csv"
)

用google-cloud-bigquery原生客户端加载示例

from google.cloud import bigquery

client = bigquery.Client()
table_id = "你的项目ID.数据集ID.表名"

# 配置加载任务,传入定义好的schema
job_config = bigquery.LoadJobConfig(schema=schema)
job = client.load_table_from_dataframe(df, table_id, job_config=job_config)
job.result()  # 等待加载任务完成

注意事项

  • 必须将时间列转换为带UTC时区的datetime对象,不能直接传递字符串列,否则会触发类型转换错误
  • 不要省略时区配置,避免本地时区干扰导致时间偏移
  • 如果目标表已存在,确保schema中的TIMESTAMP列定义与代码中一致

内容的提问来源于stack exchange,提问作者Alg_D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:01:54