0

I'm very new to Python, so I apologize for any mistaken terminology. I am trying to use matplotlib to plot data that I get from a CSV file. I've read that matplotlib only accepts timing data passed to it in the format created by strptime(). My problem arises from the fact that the time data is given to me in the format HH:MM since midnight on the day of data collection. The wrinkle is that instead of giving me the actual time in seconds, it uses a decimal fraction of a minute to represent seconds. I would like to have sub-minute resolution in my data, so how can I turn a datum like 04:26.9 into the more conventional 04:26:54 when passing each datum to strptime().

Thanks in advance :)

user3517167
  • 137
  • 1
  • 9
  • Possible duplicate of [Converting decimal time (HH.HHH) into HH:MM:SS in Python](https://stackoverflow.com/questions/32087209/converting-decimal-time-hh-hhh-into-hhmmss-in-python/)? – MPA Apr 10 '18 at 16:06

2 Answers2

1

Looks like just an algorithmic problem, there's no deal to do with matplotlib.

import time

dates = ['23:11.1', '23:15.6']

def time_mapper(t):
    hour, minsec = t.split(':')
    minute, minute_fraction = minsec.split('.')
    minute_fraction = int(minute_fraction) / 10 ** len(minute_fraction)
    seconds = '{:02d}'.format(int(60 * minute_fraction))
    t = ':'.join([hour, minute, seconds])
    return time.strptime(t, '%H:%M:%S')

list(map(time_mapper, dates))

>> [time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=23, tm_min=11, tm_sec=6, tm_wday=0, tm_yday=1, tm_isdst=-1),
    time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=23, tm_min=15, tm_sec=36, tm_wday=0, tm_yday=1, tm_isdst=-1)]
smyskov
  • 126
  • 4
1

Something like this should do the trick:

def decimal_minute_to_second(time_string):
    # partition time string into components
    hour_minute, seconds = time_string.split('.')

    # convert to seconds
    seconds = float(seconds) / 10 * 60

    # format seconds
    seconds = int(seconds) # might want to round here instead
    seconds = str(seconds)

    # reassemble
    output_string = hour_minute + ':' + seconds

    return output_string

def test(verbose=True):

    test = '04:26.9'
    expected = '04:26:54'
    actual = decimal_minute_to_second(test)

    if verbose:

        print('Test string: {}'.format(test))
        print('Expected string: {}'.format(expected))
        print('Actual string: {}'.format(actual))

    assert expected == actual

test()

# Test string: 04:26.9
# Expected string: 04:26:54
# Actual string: 04:26:54
Paul Brodersen
  • 11,221
  • 21
  • 38