Python:设置数据帧列的时区

Python: Set timezone of dataframe column

您好,我正在寻找 python 命令来为特定列设置时区。

特别是我的数据框如下所示,我想“说”“日期”列是 Europe/Berlin 时区中的日期。我不想这次转换为欧洲,这意味着 11:02:31 +2:00 是不正确的。你有什么想法把这个时间设置为Europe/Berlin时间吗?

   Index                Date  Stamp (s)     Value       Epoch
0      0 2016-07-06 11:02:31  0.1250000 0.0169273  1467802951
1      1 2016-07-06 11:02:32  1.1250000 0.0168724  1467802952
2      2 2016-07-06 11:02:33  2.1250000 0.0168620  1467802953
3      3 2016-07-06 11:02:34  3.1400000 0.0169068  1467802954
4      4 2016-07-06 11:02:35  4.1400000 0.0168702  1467802955

问候

使用tz_localize.

  df = df.assign(Date=df['Date'].dt.tz_localize('Europe/Berlin'))

nb:我更喜欢使用 assign 来避免尝试将数据设置到视图。

# core modules
from datetime import timezone, datetime

# 3rd party modules
import pandas as pd
import pytz

# create a dummy dataframe
df = pd.DataFrame({'date': [datetime(2018, 12, 30, 20 + i, 56)
                        for i in range(2)]},)
print(df)

# Convert the time to a timezone-aware datetime object
df['date'] = df['date'].dt.tz_localize(timezone.utc)
print(df)

# Convert the time from to another timezone
# The point in time does not change, only the associated timezone
my_timezone = pytz.timezone('Europe/Berlin')
df['date'] = df['date'].dt.tz_convert(my_timezone)
print(df)