Search code examples
pythondatetimematplotlibtimestrptime

Plotting time series python


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


Solution

  • 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