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

如何在Pandas DataFrame中将本地朴素时间戳转换为UTC时间

问题描述

我有一个Python函数,调用API后返回一个Pandas DataFrame。其中两个字段是时间戳,已被Pandas从字符串转换为datetime类型。问题在于API返回的时间戳为本地时区,但应用其余部分使用的均为UTC时间,因此需要将本地时间戳转换为UTC时间戳。

程序将在多种时区环境下运行,因此转换必须基于系统本地时区。

代码示例:

my_df = get_external_data(begin_time, end_time)
print(my_df.head())
print(my_df.dtypes)

示例数据:

jobid    name    user               begin                 end
0     16138    bash   noman 2022-12-13 11:33:33 2022-12-13 11:34:21
1     16139    bash   noman 2022-12-13 11:34:22 2022-12-13 11:41:47
2     16140    bash   noman 2022-12-13 11:41:49 2022-12-13 11:43:33
3     16141    bash   noman 2022-12-13 11:49:36 2022-12-13 11:43:33
4     16142    bash   noman 2022-12-13 11:57:08 2022-12-13 11:43:33
jobid                int64
name        string[python]
user        string[python]
begin       datetime64[ns]
end         datetime64[ns]
dtype: object
解决方案

要完成本地时区到UTC的转换,需要分两步操作:先给无时区信息的datetime字段标记上系统本地时区,再转换为UTC时区。以下分两种Python版本给出实现方式:

Python 3.9+(推荐)

使用Python标准库的zoneinfo模块获取系统本地时区,操作更简洁:

from zoneinfo import ZoneInfo
import pandas as pd

# 为begin和end字段添加本地时区信息
my_df['begin'] = my_df['begin'].dt.tz_localize(ZoneInfo('local'))
my_df['end'] = my_df['end'].dt.tz_localize(ZoneInfo('local'))

# 转换为UTC时区
my_df['begin'] = my_df['begin'].dt.tz_convert('UTC')
my_df['end'] = my_df['end'].dt.tz_convert('UTC')

Python 3.8及以下

使用pytz库处理时区,需先安装pytz(pip install pytz):

import pytz
import pandas as pd

# 获取系统本地时区
local_tz = pytz.tzlocal()

# 为naive datetime添加本地时区信息(is_dst=None避免夏令时歧义)
my_df['begin'] = my_df['begin'].apply(lambda x: local_tz.localize(x, is_dst=None))
my_df['end'] = my_df['end'].apply(lambda x: local_tz.localize(x, is_dst=None))

# 转换为UTC时区
my_df['begin'] = my_df['begin'].dt.tz_convert('UTC')
my_df['end'] = my_df['end'].dt.tz_convert('UTC')

说明

  • 原DataFrame中的begin和end是**无时区信息(naive)**的datetime对象,必须先标记其所属的本地时区,才能进行时区转换。
  • 两种方式都会自动识别运行环境的系统本地时区,适配多时区部署场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:23:32