Search code examples
python-3.xdatetimetimedelta

How to convert datetime string "0 days 01:32:56.696000" to minutes


I have datetime strings which are like (a) 0 days 01:32:56.696000 (b) 2 days 05:12:55.781000 etc.

I want these values to be converted to minutes. Is there is inbuilt method OR short code to do this?

Below is my code which is bit BIG. I'm looking for a more efficient way.

def index_nth_occurrence_string(original_string, find_string, nth_occurence):
    sep = original_string.split(find_string, nth_occurence)
    if len(sep) <= nth_occurence:
        return -1
    return len(original_string) - len(sep[-1]) - len(find_string)

def str_datetime_to_minute(datetime_str):
    #datetime_str format = '0 days 01:32:56.696000'
    idx_first_space = index_nth_occurrence_string(original_string=datetime_str, find_string=' ', nth_occurence=1)
    day_val = datetime_str[:idx_first_space]
    idx_second_space = index_nth_occurrence_string(original_string=val1, find_string=' ', nth_occurence=2)
    time_val = datetime_str[idx_second_space + 1:]
    hh_mm_ss = time_val.split('.')[0]
    t = hh_mm_ss.split(':')
    total_minutes = int(day_val) * 1440 + int(t[0]) * 60 + int(t[1]) * 1 + int(t[2]) / 60
    total_minutes = total_minutes.__round__(2)
    return total_minutes

val1 = '0 days 01:32:56.696000'
val2 = '2 days 05:12:55.781000'

print(f"val1 minutes = {str_datetime_to_minute(val1)}")
print(f"val2 minutes = {str_datetime_to_minute(val2)}")

Sample output:

val1 minutes = 92.93
val2 minutes = 3192.92

Solution

  • You can use datetime.datetime.strptime to parse the time portion of the input string in a more readable manner:

    from datetime import datetime
    from operator import attrgetter
    
    def str_datetime_to_minute(datetime_str):
        days, time = datetime_str.split(' days ')
        hours, minutes, seconds, microseconds = attrgetter(
            'hour', 'minute', 'second', 'microsecond'
        )(datetime.strptime(time, '%H:%M:%S.%f'))
        return (
            int(days) * 24 * 60 +
            hours * 60 +
            minutes +
            seconds / 60 +
            microseconds / 60 / 1000000
        )
    

    so that:

    str_datetime_to_minute('2 days 05:12:55.781000')
    

    returns:

    3192.9296833333333
    

    Demo: https://replit.com/@blhsing/AlarmingBumpyTags