python - 根据日期总结时间
问题描述
我有一个存储睡眠数据(常规睡眠和小睡)的数据框。以下是数据框的一些列:
- 开始时间 (YYYY-MM-DD HH:MM:SS)
- 结束时间(格式同上)
- 期间
我试图找出一种方法来总结每天的睡眠时间。查看“开始时间”并总结同一日期的时间很容易,但在有人在中午小睡但凌晨 1 点睡觉的情况下会很棘手(因为它会是第二天考虑)。
理想情况下,如果有意义的话,我希望将第二天凌晨 4 点之前的睡眠视为同一天(例如,9 月 25 日下午 5:00-7:00 午睡,9 日凌晨 2:00-7:00 睡觉) 26. 那么9/25的总睡眠量是7小时)。
关于如何使它工作的任何提示/建议?
这是我的想法(我仍然不精通 Python,所以我只是在这里和那里放置伪代码):
# Create a datetime
next_day = datetime.time(4, 0, 0)
# Create an iterator
bedtimes = iter(df['Start time'])
for i in bedtimes:
# Get current and next sleep datetime
cur = df['Start time'][i]
next = df['Start time'][i+1]
# If the next datetime in the iterator is a day after AND before
# 4:00am, add the times of 'cur' and 'next' together
# What if there is a scenario where the user takes 2 one hour naps during
# the day? What is a good way to catch that scenario as well? Use a while
# loop?
if (cur.date() < next.date()) & (next.time() < next_day):
total = cur.time() + next.time()
# Advance to the next iteration
next(bedtimes, None)
# Somehow in here, I would want the loop to skip an iteration if we
# summed 'cur' and 'next' together (since they are considered sleep
# from the same day. I am interested in calculating the amount of
# sleep PER day)
如果有错误,请更正我的语法!以上只是一个想法。如果有更好的方法,我很想听听如何做到。
提前致谢!
解决方案
推荐阅读
- r - 从 R 闪亮输入(数据存储)写入文本文件后,文本文件中只有 NULL 值
- linux - 为什么有些二进制文件在 Linux 文件系统中重复?
- web-scraping - 如何从网站上从 ESRI Arcgis 抓取/提取数据?
- java - java.lang.IllegalStateException :您指的是实际 Web 请求之外的请求属性
- ajax - 如何将jquery中onchange中的变量值发送到ajax?
- javascript - 如何从黄瓜步骤中捕获正则表达式
- google-apps-script - 为什么 DocumentApp.getUi().alert('blah') 可以在前端提醒?
- clang - 使用 Clang + msm-3.18 Kernel Android Q 构建错误
- microsoft-graph-api - 如何使用 Microsoft Graph API 获取 Teams 中的活动 PSTN 呼叫列表
- java - 如何将 XML 数据发送到当前端点的服务器