python-2.7timecodes

Convert Timecode to Frames with set start timecode


I am using the below script to convert timecode to frames, which works but is only converting with a start timecode of 00:00:00:00. I want to be able to set the start timecode so the calculation is relative. Also it breaks if I se the frame rate to 23.976 or 29.97.

framerate = 24

def timecode_to_frames(timecode):
    return sum(f * int(t) for f,t in zip((3600*framerate, 60*framerate, framerate, 1), timecode.split(':')))

def frames_to_timecode(frames):
    return '{0:02d}:{1:02d}:{2:02d}:{3:02d}'.format(frames / (3600*framerate),
                                                    frames / (60*framerate) % 60,
                                                    frames / framerate % 60,
                                                    frames % framerate)

print timecode_to_frames('00:00:00:10')
print frames_to_timecode(10)

Solution

  • If you convert your values to numeric first (eg. seconds), you can do arithmetic operations easily:

    framerate = 23.976
    
    def _seconds(value):
        if isinstance(value, str):  # value seems to be a timestamp
            _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
            return sum(f * float(t) for f,t in _zip_ft)
        elif isinstance(value, (int, float)):  # frames
            return value / framerate
        else:
            return 0
    
    def _timecode(seconds):
        return '{h:02d}:{m:02d}:{s:02d}:{f:02d}' \
                .format(h=int(seconds/3600),
                        m=int(seconds/60%60),
                        s=int(seconds%60),
                        f=round((seconds-int(seconds))*framerate))
    
    
    def _frames(seconds):
        return seconds * framerate
    
    def timecode_to_frames(timecode, start=None):
        return _frames(_seconds(timecode) - _seconds(start))
    
    def frames_to_timecode(frames, start=None):
        return _timecode(_seconds(frames) + _seconds(start))
    
    
    print(timecode_to_frames('00:00:18:10', start='00:00:05:15'))  # ~ 307
    print(frames_to_timecode(307, start='00:00:05:15'))  # '00:00:18:10'