python find the maximum of time strings

Viewed 77

I have a python list of strings which define some time interval. Something like:

intervals = ["1 days", "7 days", "30 days"]

I need to find the index of the maximum in this interval list. is there any library in python that would allow me to do this?

6 Answers

Try the parse_timespan function from humanfriendly to convert each of them, then find the maximum in the usual way?

>>> from humanfriendly import parse_timespan
>>> intervals = ["1 days", "7 days", "30 days"]
>>> parsed_intervals = [parse_timespan(interval) for interval in intervals]
>>> max(parsed_intervals)
2592000.0

If you want the original format (rather than the amount of time for further processing), you can also use:

>>> from humanfriendly import parse_timespan
>>> intervals = ["1 days", "7 days", "30 days"]
>>> max(intervals, key=parse_timespan)
'30 days'

I did it using pandas eventually. Posting it here in case it is helpful to someone.

import pandas as pd
intervals = ["1 days", "7 days", "30 days"]
deltas = [pd.Timedelta(i) for i in intervals]

idx = deltas.index(max(deltas))

This can be achieved by using core python (as seen below).

intervals = ["1 days", "7 days", "30 days"]
numbers_only = [] # creating a list to get the numbers only
for interval in intervals: # iteration through the intervals
    numbers_only.append(int(interval.split(" ")[0])) # splitting each interval on a blank space and appending just the number

max_in_nums = max(numbers_only) # using python's default library max function to get the max number in a list of numbers
print(numbers_only.index(max_in_nums)) # get the index of the number 

This code should work:

result = 0
interval = ''
for i in range(len(intervals)):
    val = int(intervals[i].split(' ')[0])
    if val > result:
        result = val
        interval = i
print(interval)
intervals = ["1 days", "7 days", "30 days"]
findmax =[]
for i in range(len(intervals)):
    n = intervals[i].replace(' days', '')
    findmax.append(float(n))
print(max(findmax))

You can use datetime.timedelta for a build-in library solution:

from datetime import timedelta
intervals = ["1 days", "7 days", "30 days"]
r = max(intervals, key=lambda x:timedelta(**{(v:=x.split())[1]:int(v[0])}))

Output:

'30 days'
Related