将 pandas 中的时间转换为 UTC

Sed*_*edi 3 python datetime timestamp utc pandas

我有多个 csv 文件,我已将 DateTime 设置为索引。

df6.set_index("gmtime", inplace=True)
#correct the underscores in old datetime format
df6.index = [" ".join( str(val).split("_")) for val in df6.index]
df6.index = pd.to_datetime(df6.index)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

时间设置为 GMT,但我认为当我为树莓派设置时钟时,它已被保存为 BST(英国夏令时)。我想把时间向后拨一小时。当我使用

df6.tz_convert(pytz.timezone('utc'))
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误,因为它假设时间是正确的。

无法转换 tz-naive 时间戳,请使用 tz_localize 进行本地化

如何将时间改为一小时?

小智 5

添加到 FObersteiner 的回复(抱歉,新用户,还不能评论答案):

我注意到,在我遇到过的所有现实情况中(使用完整的数据帧或 pandas 系列而不是单个日期), .tz_localize() 和 .tz_convert() 的调用方式需要略有不同。

对我有用的是

df['column'] = pd.to_datetime(df['column']).dt.tz_localize('Europe/London').dt.tz_convert('UTC')
Run Code Online (Sandbox Code Playgroud)

如果没有 .dt,我会得到“索引不是有效的 DatetimeIndex 或 periodIndex”。