根据一天中的时间舍入日期时间 [英] Rounding datetime based on time of day

查看:98
本文介绍了根据一天中的时间舍入日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据帧,其时间戳如下所示:

I have a pandas dataframe with timestamps shown below:

2019/6/30 3:45:00 PM

我想根据时间取整日期。上午6点之前的任何时间都将算作前一天。

I would like to round the date based on time. Anything before 6AM will be counted as the day before.

6/30/2019  5:45:00 AM -> 6/29/2019
6/30/2019  6:30:00 AM -> 6/30/2019

我考虑做的是将日期和时间分为2个不同的列然后使用一个if语句来移动日期(如果时间> = 06:00等)。只是想知道熊猫中是否有内置功能可以做到这一点。我见过有人根据最接近的时间向上或向下四舍五入的信息,但从来没有指定时间阈值(6AM)。

What I have considered doing is splitting date and time into 2 different columns then using an if statement to shift the date (if time >= 06:00 etc). Just wondering there is a built in function in pandas to do this. Ive seen posts of people rounding up and down based on the closest hour but never a specific time threshold (6AM).

感谢您的帮助!

推荐答案

可能会有更好的方法。但这是一种方法。

there could be a better way to do this.. But this is one way of doing it.

import pandas as pd    

def checkDates(d):
    if d.time().hour < 6:
        return d - pd.Timedelta(days=1)
    else:
        return d

ls = ["12/31/2019  3:45:00 AM", "6/30/2019  9:45:00 PM", "6/30/2019  10:45:00 PM", "1/1/2019  4:45:00 AM"]
df = pd.DataFrame(ls, columns=["dates"])
df["dates"] = df["dates"].apply(lambda d: checkDates(pd.to_datetime(d)))
print (df)
                dates
0 2019-12-30 03:45:00
1 2019-06-30 21:45:00
2 2019-06-30 22:45:00
3 2018-12-31 04:45:00

还要注意,我没有考虑时间。当返回结果时..
如果只想将日期作为结尾,则可以将它从datetime对象中取出,做这样的事情

Also note i am not taking into consideration of the time. when giving back the result.. if you just want the date at the end of it you can just get that out of the datetime object doing something like this


打印((pd.to_datetime( 12/31/2019 3:45:00 AM))。date())>>> 2019-12-31

print ((pd.to_datetime("12/31/2019 3:45:00 AM")).date()) >>> 2019-12-31

如果很好地理解python,并且不希望其他人(以后)了解您在做什么
上面的方法是

if understand python well and dont want anyone else(in the future) to understand what your are doing one liner to the above is.

df["dates"] = df["dates"].apply(lambda d: pd.to_datetime(d) - pd.Timedelta(days=1) if pd.to_datetime(d).time().hour < 6 else pd.to_datetime(d))

这篇关于根据一天中的时间舍入日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆