【问题标题】:Timezone conversion error found when converting the timezone of a large list of timestamps in an excle file with python使用python转换excle文件中大量时间戳的时区时发现时区转换错误
【发布时间】:2018-10-13 00:22:08
【问题描述】:

我有一个名为“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

我在网上搜索了一个解决方案,但未能正确解决。我希望有人可以帮助弄清楚。新方法也受到欢迎。谢谢~:)

【问题讨论】:

  • 你从哪里得到这个答案的?这对于选择该方法的原因很有用。
  • 我猜来自here
  • 首先使用print (df[0].dtype)检查df[0]的数据类型是什么。如果这给出了datetime64[ns],那么上面的代码应该可以工作。否则,您需要进行数据类型转换。还要检查这个answer

标签: python excel timezone timestamp


【解决方案1】:

问题是您尝试将 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)

【讨论】:

  • 我怀疑df[0] = df[0].apply(lambda x: datetime.strptime(x, local_fmt)) 使用df[0] = pandas.to_datetime(df[0], format="%m/%d/%Y %H:%M:%S") 会更快
猜你喜欢
  • 2018-10-12
  • 2011-12-15
  • 2014-02-12
  • 2018-11-26
  • 2011-05-10
  • 2019-09-11
  • 2011-12-24
  • 2021-09-22
  • 1970-01-01
相关资源
最近更新 更多