【问题标题】:Transform date to timestamp python将日期转换为时间戳 python
【发布时间】:2020-01-24 10:32:44
【问题描述】:

我有一个特殊问题,我有一个包含 2 列的 Dataframe,一个是 date_x,另一个是 timestamp,它是 hour:min:sec,所以我试图将 timestamp 列转换为 Unix 时间戳.

我尝试过的事情是这样的:

df.timestamp = df.timestamp.apply(lambda x: pd.datetime.strptime(x, "%H:%M:%S").timestamp())

但重点是我不仅需要hour,min,second。正确的格式是%Y-%m-%d %H:%M:%S,但我不知道如何包含date 列,因为它将是date_x + timestamp

【问题讨论】:

  • 试试 strftime。 datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  • @ShwetaChandel 我需要从 cols = date_x + timestamp 获取信息才能获得这种格式: date_x(YYYY-MM-dd) + timestamp(H-M-S) 但我不知道如何正确地做到这一点!

标签: python pandas dataframe timestamp


【解决方案1】:

将列转换为timedeltas并添加到DatetimeIndex,最后转换为unix时间戳:

print (df)
           timestamp
2018-02-02  17:01:15
2018-02-02  17:01:18
2018-02-02  17:01:24
2018-02-02  08:32:57
2018-02-02  08:33:02
2018-02-02  08:33:08

arr = (df.index + pd.to_timedelta(df.timestamp)).values.astype(np.int64) // 10 ** 6
print (arr)
[1517590875000 1517590878000 1517590884000 1517560377000 1517560382000
 1517560388000]

【讨论】:

  • 这行得通!但是给我加了很多零!数组([1517590875000000000, 1517590878000000000, 1517590884000000000, ..., 1517560377000000000, 1517560382000000000, 151756038800=000000000, 151756038800=0060d]
  • @Peter - 没有错过// 10 ** 6 ?
  • 糟糕!你是对的!这就是解决方案!谢谢!
【解决方案2】:
pd.to_datetime(df.index.strftime("%Y/%m/%d") +' '+ df.timestamp).values.astype(np.int64) // 10 ** 6

首先使用strftime("%Y/%m/%d")将索引更改为str格式以加入datetimestamp
然后通过pd.to_datetime
转换成日期时间 最后转换为int64 作为时间戳

【讨论】:

  • 看起来不错,但是 date_x 它是我的索引 col 所以不能做 df.date_x!
  • 使用df.index 代替df.date_x + ...
  • TypeError: +: 'DatetimeIndex' 和 'str' 的不支持的操作数类型及其 dtype('
  • >>> pd.to_datetime(df.index.strftime("%Y/%m/%d") +' '+ df.a).values.astype(np.int64) // 10 ** 6 先将其转换为 str 甲酸盐
  • 请在您的代码中添加一些解释,以便其他人可以从中学习
猜你喜欢
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 2020-06-15
  • 1970-01-01
  • 2019-02-16
  • 2016-02-10
相关资源
最近更新 更多