pythondatetimehumanize

Python create time interval from human readable string


Is there a Python library to convert human readable time interval to 2 datetimes?

Example:

Str(TimeInterval("last week")) # return a tuple (datetime(2023,11,12,0,0,0), datetime(2023,11,19,23,59,59))

Same for today, yesterday, last month, 2 months ago, year-to-date, etc.


Solution

  • As far as I know, there is no direct converter. But, with the pendulum library, you can implement it easily by using now.subtract() (as parameter days, months, years):

    yesterday: now.subtract(days=1)
    last week: now.subtract(weeks=1).start_of('week'), .end_of('week')
    last month: now.subtract(months=1).start_of('month'), .end_of('month')
    last year: now.subtract(years=1).start_of('year'), .end_of('year')
    

    Sample Code:

    import pendulum
    
    def human_readable(interval):
        now = pendulum.now()
        if interval.lower() == 'today':
            return now.start_of('day'), now.end_of('day')
        elif interval.lower() == 'yesterday':
            yesterday = now.subtract(days=1)
            return yesterday.start_of('day'), yesterday.end_of('day')
        elif interval.lower() == 'last week':
            start_last_week = now.subtract(weeks=1).start_of('week')
            end_last_week = now.subtract(weeks=1).end_of('week')
            return start_last_week, end_last_week
        elif interval.lower() == 'last month':
            start_last_month = now.subtract(months=1).start_of('month')
            end_last_month = now.subtract(months=1).end_of('month')
            return start_last_month, end_last_month
        elif interval.lower() == '2 months ago':
            start_date = now.subtract(months=2).start_of('month')
            end_date = now.subtract(months=2).end_of('month')
            return start_date, end_date
    
    intervals = ['last week', 'last month', '2 months ago']
    for interval in intervals:
        start_date, end_date = human_readable(interval)
        print(f"{interval}: {start_date},  {end_date}")
    

    Output:

    last week: 2023-11-13T00:00:00+01:00,  2023-11-19T23:59:59.999999+01:00
    last month: 2023-10-01T00:00:00+02:00,  2023-10-31T23:59:59.999999+01:00
    2 months ago: 2023-09-01T00:00:00+02:00,  2023-09-30T23:59:59.999999+02:00