Skip to content
Advertisement

Days between dates into minimum non-date measurement

I have a column that represents the number of days from an event until today.

daysSeries = pd.Series([2, 13,29,31,91,180,367,725],dtype=int64)

I am trying to figure out a way to represent this as a string such that it shows the rounded number of days / weeks / months / years. However, I would like it to choose “D”/”W”/”M”/”Y” based on the minimum value of each that is > 1. Some rounding is fine to make sure that a few days off doesnt mess it all up.

For example, if the input number is 31, I don’t want “4Weeks”, but instead “1Month”.

Using the example values about, I would expect:

["2Days", "2Weeks", "1Month", "1Month", "3Month", "6Months", "1Year", "2Year"].

Advertisement

Answer

I did it without the round, it’s much easier that way:

import pandas as pd

def lowest_str(days: int) -> str:
    if days >= 365:
        return f'{days // 365} Years'
    if days >= 30:
        return f'{days // 30} Months'
    if days >= 7:
        return f'{days // 7} Weeks'
    return f'{days} Days'


daysSeries = pd.Series([2, 13, 29, 31, 91, 180, 367, 725])
print(daysSeries.apply(lowest_str))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement