python: moving selected keys only



I am writing a python script to offset some keys on objects.
I get the selected objects, then I want to go through the selected objects and offset each object’s selected keyframes a certain amount.
I can get the selected keys using

cmds.keyframe (query=True, sl=True )

and I can move all selected key of all selected objects using:


but I can’t figure out a way to move only selected keys of a single object from the selected objects list:

import maya.cmds as cmds
selected =
amount =2
for sel in range (0,len(selected)):

the above code moves all keys of selected objects, and not just the selected keys of the selected objects.
I tried getting the selected keys of the selected object inside the for-loop, and feed this variable to the “keyframe” command, instead of the object name (selected[sel]), but I get an error…
anyone can help me get this right? :slight_smile:


I think you will need to pull out the selected keys on each object and use them to specify what you want the keyframe command to operate on. Here’s an example that operates on all animation of the given object at the times of its selected keys. That may or may not be too broad but it should give you an idea (this is simplified for testing purposes, I skipped your index-based multiplier on the time change):

import maya.cmds as cmds

selected =
amount = 2

for sel in selected:
    activeKeyTimes = cmds.keyframe(sel, q=True, sl=True)
    for t in activeKeyTimes:
        cmds.keyframe(sel, edit=True, time=(t,t), relative=True, timeChange=amount)


Hi, thanks but this works halfway… it offsets selected keys, but it also offsets unselected keys on other channels, if they are on the same frame(s) as the selected ones that are offsetted.


That’s what I meant by “may or may not be too broad,” it should be easy to account for individually selected channels though:

import maya.cmds as cmds

selected =
amount = 2

for obj in selected:
    nodes = cmds.keyframe(obj, q=True, name=True, sl=True)
    for node in nodes:
        activeKeyTimes = cmds.keyframe(node, q=True, sl=True, tc=True)
        for t in activeKeyTimes:
            cmds.keyframe(node, edit=True, time=(t,t), relative=True, timeChange=amount)


Thanks Spire2! that really helps me :):thumbsup: