使用python转换excle文件中的大型时间戳列表的时区时发现时区转换错误

时间:2018-05-02 19:37:36

标签: python excel timezone timestamp

我有一个名为“hello.xlsx”的excel文件。有一列时间戳有很多行(现在超过80,000行)。该文件基本上如下所示:

04/19/2018 01:37:33

04/19/2018 01:37:54

04/19/2018 01:37:57

04/19/2018 01:37:59

04/19/2018 01:38:05

04/19/2018 01:38:10

04/19/2018 01:38:38

04/19/2018 01:39:29

04/19/2018 01:39:32

04/19/2018 01:39:44

04/19/2018 01:39:51

等等......

这些时间戳是UTC时间,我需要将它们转换为美国太平洋时间(UTC,-7)。

我是python的初学者,实际上我不知道如何进行这样的转换。我在网上问了一个有用的答案。代码如下所示:

df = pd.read_excel('hello.xlsx', header=None)

local_tz = pytz.timezone('US/Pacific')

df[0] = df[0].apply(lambda x: x.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None))

df.to_excel('out.xlsx', index=False, header=False)

但是,运行后出现错误:

TypeError: replace() takes no keyword arguments

我在网上搜索寻找解决方案但未能做到正确。我希望有人能帮到解决这个问题。新方法也受到欢迎。谢谢〜:)

1 个答案:

答案 0 :(得分:0)

问题是您尝试将方法从datetime类应用于str对象。 在应用时区转换之前,您需要将从Excel文件中读取的字符串转换为datetime对象。

import pandas as pd
import pytz
from datetime import datetime

df = pd.read_excel('hello.xlsx', header=None)
local_tz = pytz.timezone('US/Pacific')
local_fmt = "%m/%d/%Y %H:%M:%S"

df[0] = df[0].apply(lambda x: datetime.strptime(x, local_fmt))
df[0] = df[0].apply(lambda x: x.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None))
df.to_excel('out.xlsx', index=False, header=False)