将日期转换为时间戳Python

时间:2020-01-24 10:32:44

标签: python pandas dataframe timestamp

我有一个特殊的问题,我有一个包含两列的数据框,其中一列为date_x,另一列为timestamp,其列为hour:min:sec,所以我试图转换{{ 1}}列为Unix时间戳。

我已经尝试过的东西:

timestamp

但要指出的是,我不仅需要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

2 个答案:

答案 0 :(得分:0)

pd.to_datetime(df.index.strftime("%Y/%m/%d") +' '+ df.timestamp).values.astype(np.int64) // 10 ** 6

首先使用strftime("%Y/%m/%d")datetimestamp列合并为str格式的索引
然后通过pd.to_datetime
转换为日期时间 最后转换为int64以获得时间戳

答案 1 :(得分:0)

将列转换为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]