首页 > 解决方案 > 将纪元时间戳列转换为纪元中每月的第一天

问题描述

我有一个纪元时间戳列,如下所述。我需要将此纪元时间戳列转换为该月的第一天,并且输出也应该在纪元中。

time_stamp
1528974011
1530867602
1530867602
1530867604
1530867602
1528974012
1528974011

示例:上列中的第一个值1530867602对应14/06/2018 11:00:11于日期时间格式。现在,同一日期的一个月的第一天是01/06/2018我想要的纪元格式。

这也可以通过以下步骤来实现:

epoch->datetime->first_day_of_the_month->epoch_first_day_of_the_month

但是有没有更好的方法来做同样的事情?

提前致谢!

如果对此有任何问题/资源,请提及

标签: pandasdataframepython-datetime

解决方案


采用:

#convert to datetimes
df['time_stamp'] = pd.to_datetime(df['time_stamp'], unit='s')

#first day of month
df = df.resample('MS', on='time_stamp').first()
print (df)
                    time_stamp
time_stamp                    
2018-06-01 2018-06-14 11:00:11
2018-07-01 2018-07-06 09:00:02

print (df['time_stamp'].index.floor('d'))
DatetimeIndex(['2018-06-01', '2018-07-01'], 
               dtype='datetime64[ns]', name='time_stamp', freq=None)

#remove times and convert to epoch
out = (df['time_stamp'].index.floor('d').astype(np.int64) // 10**9)
print (out)
Int64Index([1527811200, 1530403200], dtype='int64', name='time_stamp')

另一种解决方案是将列转换为月份,然后转换为月份的第一天:

df['time_stamp'] = (pd.to_datetime(df['time_stamp'], unit='s')
                      .dt.to_period('M')
                      .dt.to_timestamp())

然后删除重复项并转换为纪元:

df = df.drop_duplicates('time_stamp').astype(np.int64) // 10**9
print (df)

   time_stamp
0  1527811200
1  1530403200

推荐阅读