首页 > 解决方案 > 根据日期总结时间

问题描述

我有一个存储睡眠数据(常规睡眠和小睡)的数据框。以下是数据框的一些列:

我试图找出一种方法来总结每天的睡眠时间。查看“开始时间”并总结同一日期的时间很容易,但在有人在中午小睡但凌晨 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)

如果有错误,请更正我的语法!以上只是一个想法。如果有更好的方法,我很想听听如何做到。

提前致谢!

标签: pythondatedataframetimesum

解决方案


推荐阅读