Python:设置数据框列的时区

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


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


   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


慕神8447489
浏览 94回答 2
2回答

HUH函数

使用 tz_localize。  df = df.assign(Date=df['Date'].dt.tz_localize('Europe/Berlin'))nb:我更喜欢使用 assign 来避免尝试将数据设置到视图。

MMMHUHU

# core modulesfrom datetime import timezone, datetime# 3rd party modulesimport pandas as pdimport pytz# create a dummy dataframedf = 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 objectdf['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 timezonemy_timezone = pytz.timezone('Europe/Berlin')df['date'] = df['date'].dt.tz_convert(my_timezone)print(df)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python