Home > Software engineering >  What is ceil("1d") with reference to timedeltas in Python
What is ceil("1d") with reference to timedeltas in Python

Time:11-30

I have a function I have come across:

def sub_kpi1_rule(sub_comp_appr_date, date_report_run, greater_of_date_sub_sub_ll):
        if pd.isnull(sub_comp_appr_date) and not alive_for_six_days(date_report_run, greater_of_date_sub_sub_ll):
            return "NA"
        elif (sub_comp_appr_date - greater_of_date_sub_sub_ll).ceil("1d").days <= 6:
            return "PASS"
        else:
            return "FAIL"

all arguments are date types, so I am assuming:

(sub_comp_appr_date - greater_of_date_sub_sub_ll)

...returns a timedelta instance. I am confused about this ceil(syntax)

elif (sub_comp_appr_date - greater_of_date_sub_sub_ll).ceil("1d").days <= 6:

because if I try and subtract two dates and use this function, I get an error:

from datetime import date
a = date(2022, 10,1)
b = date(2022, 10,15)
(b-a).ceil("1d")


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [36], line 4
      2 a = date(2022, 10,1)
      3 b = date(2022, 10,15)
----> 4 (b-a).ceil("1d")

AttributeError: 'datetime.timedelta' object has no attribute 'ceil'

The function is called on a data frame:

df["Sub KPI1"] = df.apply(lambda x: sub_kpi1_rule(x["SUBM_LATE_DESTINATION_COMPLIANCE_APPROVAL_DATE"], date_report_run, x["Greater of Date Submitted and Submission LL Created"]), axis=1)

I think the types are pd.Timestamp, as date_report_run is explicitly converted to one:

date_report_run = date(year_report_run, month_report_run, day_report_run)
date_report_run = pd.Timestamp(date_report_run)

I am guessing I am getting a pandas._libs.tslibs.timedeltas.Timedelta back rather than a normal timedelta.

CodePudding user response:

You get an error, because you're using .ceil() on datetime.timedelta class in your example. You need the pandas class for this. (pandas._libs.tslibs.timedeltas.Timedelta)

delta = pd.Timedelta(4, "d")

Now, what does this .ceil("1d") do? If you have a delta with hours and minutes you want ceil it to days value. E.g.:

date1 = pd.to_datetime(1490195805, unit='s')
date2 = pd.to_datetime(1490597688, unit='s')
date2 - date1

Timedelta('4 days 15:38:03')

(date2 - date1).ceil("1d")

Timedelta('5 days 00:00:00')

As the hours are more than 12h, the date delta gets ceiled to 5 days.

  • Related