Luca
Luca

Reputation: 10996

python find the maximum of time strings

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?

Upvotes: 1

Views: 121

Answers (6)

Ajax1234
Ajax1234

Reputation: 71451

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'

Upvotes: 0

Sunjid
Sunjid

Reputation: 70

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)

Upvotes: 0

Karina
Karina

Reputation: 1280

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))

Upvotes: 0

Brett La Pierre
Brett La Pierre

Reputation: 533

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 

Upvotes: 0

Luca
Luca

Reputation: 10996

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))

Upvotes: 1

Jiří Baum
Jiří Baum

Reputation: 6930

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'

Upvotes: 3

Related Questions