[Python] calculate age in python using numpy/any other package which considers US Holidays +...

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    I want to calculate the age (Day & Hr e.g. 1 Day 8Hr ) since the record was created. But it should not consider the weekend + US holidays.

    Currently, I am using Numpy, but if some other package can do the same, then it's fine for me

    Issues using numpy:


    1. While using numpy function busday_count, this function does consider time, i.e., if a record is created on 1st June at 10 AM and and current time is 2nd June at 8 AM then this function still gives me day difference 1, but its not correct age 1 day will get completed at 2nd June 10 AM so the date count which I want should be 0


    2. As per my knowledge, there is nothing in numpy for calculating time difference which takes weekends and us holidays into consideration like the busday_count function of numpy

    import holidays


    def age(self):
    dates = []
    current_year = timezone.now().year
    for i in holidays.US(
    years=[current_year - 1, current_year, current_year + 1]
    ).keys():
    dates.append(i)
    bdd = np.busdaycalendar(holidays=dates)

    # Get day difference
    day = np.busday_count(
    self.record_created_at.date(), timezone.now().date(), busdaycal=bdd
    )

    age = timezone.now() - self.record_created_at

    # Get time difference
    hour = math.ceil(age.seconds / 60 / 60) - 1
    data = {"day": day, "hour": hour, "label": f"{day}d {hour}h"}
    return data

    Continue reading...

Compartilhe esta Página