1

I have a file containing alerts occurence time. I want to sort those in ascending order. Can you please guide me about this.

Sample time format.

1 day, 19 hours
3 weeks
4 weeks, 1 day
2 minutes
1 month, 1 week
10 hours, 36 minutes
4 weeks, 1 day
4 weeks, 1 day
13 minutes
5 hours, 16 minutes
1 hour, 53 minutes
3 hours, 18 minutes
21 hours, 42 minutes
18 hours, 49 minutes
21 hours, 43 minutes
3
  • It's easier to sort numbers than it is to sort phrases. Without necessarily writing the code to do it, how would you convert each of these phrases into a number...perhaps a duration in seconds? Commented May 8, 2019 at 6:53
  • sed -E 'h;s/(month|week|day|hour|minute|second)\>/&s/g;s/,//g;s/.*/date -d "+&" +%s/e;G;s/\n/\t/' file | sort | cut -f 2 :D Commented May 8, 2019 at 7:00
  • Thank you very much its working as expected. Commented May 8, 2019 at 7:19

1 Answer 1

2

Maybe not super elegant, but straight forward in Python:

#!/usr/bin/env python                                                           

import operator

# 1 month = 28-31 days and 4 weeks = 28 days, so month is kept separate
time_in_seconds = {
    'week': 7*24*60*60,
    'day': 24*60*60,
    'hour': 60*60,
    'minute': 60,
    'second': 1
}

if __name__ == '__main__':
    times = []

    with open('sample_time.txt', 'r') as f:
        for line in f.read().split('\n'):
            months = 0
            seconds = 0
            try:
                for pair in line.split(', '):
                    num, denum = pair.split(' ')
                    if denum.startswith('month'):
                        months += int(num)
                    else:
                        seconds += time_in_seconds[denum.rstrip('s')]*int(num)
                times.append([months, seconds, line])
            except:
                pass

    sorted_times = sorted(times, key=operator.itemgetter(0,1))
    for line in map(operator.itemgetter(2), sorted_times):
        print(line)

It assumes your file is called sample_time.txt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.