【问题标题】:python | arrow.get error and replace serial number with real time蟒蛇 | arrow.get 错误并用实时替换序列号
【发布时间】:2021-12-26 06:09:54
【问题描述】:

以下是股票价格数据,我将其保存到 DataFrame 中。 t 列是代表时间的序列号。

a b t
1.20 5.45 1636534800000
7.98 1.33 1636542000000
8.29 2.44 1636549200000
8.76 6.55 1636556400000
  1. 如果我输入 arrow.get(1636534800000),那么我会得到 2021-11-10T09:00:00+00:00 没有问题

但是,执行以下操作时出现错误。注意t列的数据类型是int64

trade_date = df.loc[0,'t'] 
date_reformat=arrow.get(trading_date)

错误信息:

"raise TypeError(f"Cannot parse single argument of type {type(arg)!r}.") TypeError: Cannot parse single argument of type ."

  1. 我需要一个代码来将 t 列中的值替换为“实时”而不是序列号。 t 列中的值是 UTC 时区,我住在美国东海岸,所以我需要它来调整回东部时间。但是我们有夏令时。我们目前处于 EST 时区,3 月后我们将前往 EDT 时区。因此,如果时间在 3 月和 11 月之间,则 t 应调整为 UTC-4,其余时间 t 列应调整为 UTC-5。我不需要“+00:00”,我只需要那个 year-month-dateThh:mm:ss

【问题讨论】:

  • 不确定它为什么起作用,但是用 int() 包装你的 trade_date。 trade_date = int(df.loc[0,'t']) date_reformat=arrow.get(trade_date)

标签: python pandas date datetime


【解决方案1】:

您的输入是以毫秒为单位的 UNIX 时间(自 1970-01-01 UTC 起)。使用

转换为日期时间
df['datetime'] = pd.to_datetime(df['t'], unit='ms', utc=True)

设置utc=True 将指定日期/时间为UTC(不是本地时间等)。现在您可以转换为美国/东部时区来说明 DST 活动/非活动:

df['datetime'] = df['datetime'].dt.tz_convert('America/New_York')

并转换为具有特定格式的字符串,例如不显示 UTC 偏移量:

df['datetime_string'] = df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')

这给了你一个例子:

df[['datetime', 'datetime_string']]

                   datetime      datetime_string
0 2021-11-10 04:00:00-05:00  2021-11-10 04:00:00
1 2021-11-10 06:00:00-05:00  2021-11-10 06:00:00
2 2021-11-10 08:00:00-05:00  2021-11-10 08:00:00
3 2021-11-10 10:00:00-05:00  2021-11-10 10:00:00

【讨论】:

  • 完美运行!!!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 2018-08-24
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
相关资源
最近更新 更多