Johnny
Johnny

Reputation: 43

Convert a list of minutes into lists of minutes, hours, days and months in python

I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

Minutes
21601
30
0
90000

Resulting lists:

Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.
Cheers,

Upvotes: 0

Views: 1024

Answers (5)

Ramakanth Putta
Ramakanth Putta

Reputation: 726

You can use the below method

def format (minutes):
    year = (int) (minutes/(12*30*24*60))
    month = ((int) (minutes/(30*24*60)))%12
    day = ((int) (minutes/(24*60)))%30
    hour = ((int) (minutes/(60)))%24
    min = ((int) (minutes))%60
    return [min,hour,day,month,year]

lis = [21601,30,0,90000]
ans = list(map(lambda x: format(x) , lis))
print(ans)

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78564

You can wrap the division/remainder operations into one using the builtin function divmod:

rem, minutes = zip(*(divmod(x, 60) for x in list_minutes))
rem, hours = zip(*(divmod(x, 24) for x in rem))
months, days = zip(*(divmod(x, 30) for x in rem))

Of course, you can use the datetime.timedelta function to get a timedelta from your minutes, however, this would still require some extra math ops to get the months and hours.

Upvotes: 1

Buddyshot
Buddyshot

Reputation: 1684

You could use a timedelta object together with a datetime.

Example:

from datetime import timedelta, datetime

def convert_from_minutes(minutes):
    td = timedelta(minutes=minutes)
    dt = datetime(1,1,1)
    result = dt + td
    return {
        "days": result.day-1,
        "hours": result.hour,
        "minutes": result.minute,
        "seconds": result.second
    }

ans = convert_from_minutes(21601)
ans["days"]     # gives 15
ans["hours"]    # gives 0
ans["minutes"]  # gives 1
ans["seconds"]  # gives 0

Upvotes: 1

sharath
sharath

Reputation: 3626

Another way of doing this would be to use datetime.timedelta.

from datetime import datetime, timedelta

d = timedelta(minutes=90000)
print("DAYS:SECONDS")
print("%d:%d" % (d.days, d.seconds))

This gives you:

DAYS:SECONDS 62:43200

You can always convert that to which ever date format you want

Upvotes: 2

Johnny
Johnny

Reputation: 43

Ok, I found a way around, though I don't if this is the nicest way but it seems to work:

# list_minutes -is a list of minutes 
minutes=[x % 60 for x in list_minutes]
remeinder1=[x // 60 for x in list_minutes]
hours=[x % 24 for x in remeinder1]
remeinder2=[x // 24 for x in remeinder1]
days=[x % 30 for x in remeinder2]
month=[x % 30 for x in remeinder2]

Cheers.

Upvotes: 0

Related Questions