【问题标题】:pandas converting datetime to epoch with correct timezone熊猫将日期时间转换为具有正确时区的纪元
【发布时间】:2017-02-07 19:51:45
【问题描述】:

我有一个像这样的简单数据框

                Started
job
446 2016-09-29 08:53:24
447 2016-09-29 08:54:37
448 2016-09-29 08:55:49
449 2016-09-29 08:57:00
450 2016-09-29 08:58:12

我想将此日期时间转换为具有正确时区的纪元。所以我在做

df['started_epoch']=df['Started'].astype(np.int64)//10**9

这可行,但我得到的时代是 UTC。如何获得 EDT?

【问题讨论】:

  • 纪元假定为UTC。如果您要将它移动几个小时,那么它就不再是时代了。参考:epochconverter.com

标签: datetime pandas


【解决方案1】:

我觉得你需要tz_localize:

#dtype of Started is datetime
df['started_epoch'] = df.Started.dt.tz_localize('EST5EDT').astype(np.int64)//10**9
print (df)
   job             Started  started_epoch
0  446 2016-09-29 08:53:24     1475153604
1  447 2016-09-29 08:54:37     1475153677
2  448 2016-09-29 08:55:49     1475153749
3  449 2016-09-29 08:57:00     1475153820
4  450 2016-09-29 08:58:12     1475153892

我尝试测试它,它似乎有效:

df['started_epoch'] = df.Started.dt.tz_localize('EST5EDT').astype(np.int64)//10**9
df['started_epoch1'] = df.Started.astype(np.int64)//10**9
print (df)
   job             Started  started_epoch  started_epoch1
0  446 2016-09-29 08:53:24     1475153604      1475139204
1  447 2016-09-29 08:54:37     1475153677      1475139277
2  448 2016-09-29 08:55:49     1475153749      1475139349
3  449 2016-09-29 08:57:00     1475153820      1475139420
4  450 2016-09-29 08:58:12     1475153892      1475139492

【讨论】:

  • 当我尝试这样做时,我遇到了类型错误 *** TypeError: long() 参数必须是字符串或数字,而不是“时间戳”
  • 那么df['started_epoch'] = df.Started.astype(np.int64)//10**9 有效吗?
  • 好像不可能,见最后note
  • 还有其他建议吗?
  • 但也许你需要先转换为UTCdf['started_epoch'] = df.Started.dt.tz_localize('UTC').dt.tz_localize('EST5EDT').astype(np.int64)//10**9
猜你喜欢
  • 2021-05-02
  • 2020-02-22
  • 1970-01-01
  • 2014-05-19
  • 2019-08-22
  • 2012-09-06
  • 2018-04-24
  • 2011-12-06
  • 2021-12-20
相关资源
最近更新 更多