如何将 pandas 日期时间列从 UTC 转换为 EST

问题描述 投票:0回答:3

还有一个十一年前的问题,也有类似的标题。

我有一个 pandas 数据框,其中包含一列 datetime.time 值。

val    time
a      12:30:01.323
b      12:48:04.583
c      14:38:29.162

我想将时间列从 UTC 转换为 EST。

我尝试做

dataframe.tz_localize('utc').tz_convert('US/Eastern')
,但它给了我以下错误:
RangeIndex Object has no attribute tz_localize

python pandas time timezone
3个回答
5
投票

to_datetime
接受参数
utc (bool)
,当为 true 时,将时间戳强制为 utc。

to_datetime
返回一个
DateTimeIndex
,它有一个方法
tz_convert
。此方法会将 tz 感知时间戳从一种时区转换为另一种时区。

因此,这个转换可以简写为

df = pd.DataFrame(
       [['a', '12:30:01.323'],
        ['b', '12:48:04.583'],
        ['c', '14:38:29.162']],
       columns=['val', 'time']
)
df['time'] = pd.to_datetime(df.time, utc=True, format='%H:%M:%S.%f') 
# convert string to timezone aware field ^^^
df['time'] = df.time.dt.tz_convert('EST').dt.time
# convert timezone, discarding the date part ^^^

这会产生以下数据框:

  val             time
0   a  07:30:01.323000
1   b  07:48:04.583000
2   c  09:38:29.162000

这也可以是如下所示的 1 行:

pd.to_datetime(df.time, utc=True, format='%H:%M:%S.%f').dt.tz_convert('EST').dt.time

4
投票

tz_localize
tz_convert
用于 DataFrame 的索引。所以你可以执行以下操作:

  1. 将“时间”转换为时间戳格式
  2. 将“时间”列设置为索引并使用转换函数
  3. reset_index()
  4. 只保留时间

尝试:

dataframe["time"] = pd.to_datetime(dataframe["time"],format="%H:%M:%S.%f")
output = (dataframe.set_index("time")
                   .tz_localize("utc")
                   .tz_convert("US/Eastern")
                   .reset_index()
          )
output["time"] = output["time"].dt.time

>>> output
              time val
0  15:13:12.349211   a
1  15:13:13.435233   b
2  15:13:14.345233   c

1
投票
list_temp = []
for row in df['time_UTC']:
    list_temp.append(Timestamp(row, tz = 'UTC').tz_convert('US/Eastern'))
df['time_EST'] = list_temp
© www.soinside.com 2019 - 2024. All rights reserved.