pandas - 将纪元时间戳列转换为纪元中每月的第一天
问题描述
我有一个纪元时间戳列,如下所述。我需要将此纪元时间戳列转换为该月的第一天,并且输出也应该在纪元中。
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
但是有没有更好的方法来做同样的事情?
提前致谢!
如果对此有任何问题/资源,请提及
解决方案
采用:
#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
推荐阅读
- azure - 用于 GetKey 的 Azure KeyVaultClient 机密
- reactjs - 如果在反应单元测试中的返回语句中未采用路径
- laravel - 使用 Laravel 日志文件进行调试
- android - 如何为每个页面加载颤动在 Web 视图中实现进度指示器?
- html - 什么 VSCode 语言配置设置允许 HTML 在输入时在标签中添加额外的行?
- android - React Native 发布崩溃
- angular - 是否可以在 Angular 中覆盖(单击)自定义组件的绑定信息?
- reactjs - 道具更改时反应不重新渲染组件
- python - 排行榜抛光 discord.py
- java - 试图在java中本地创建一个表达式eval函数