<p>I am using the following command to gracefully delete any stale pods in <em>Pending</em> state:</p>
<p><code>kubectl get pod -n my-namespace | grep Pending | awk '{print $1}' | xargs kubectl delete pod -n my-namespace</code></p>
<p>However, I would like to add a condition that deletes only those pods who have been in pending state for more than N hours. There is the <code>AGE</code> column returned with <code>get pods</code> but its time unit varies and I am assuming there is a better way.</p>
<p>Also would appreciate if anyone can mention any best practices around this as I aim to run this command periodically to cleanup the pending Pods.</p>

Kamal Memon
<p>It is difficult to calculate how much time a Pod has spent in a particular Status by using <code>kubectl</code> solely and without a help of some 3rd party tools. However, I got a solution that you may find useful.</p>
<p>You can list all Pods that are in <code>Pending</code> state <strong>and</strong> are older than X days. For example, the command below will list all <code>Pending</code> Pods that are older than 5 days:</p>
<pre><code>kubectl get pods --field-selector=status.phase=Pending --sort-by=.metadata.creationTimestamp | awk 'match($5,/[6-9]d|[0-9][0-9]d|[0-9][0-9][0-9]d/) {print $0}'
</code></pre>
<p>Than you can use the next command to delete these pods:</p>
<pre><code>kubectl delete pod $(kubectl get pods --field-selector=status.phase=Pending --sort-by=.metadata.creationTimestamp | awk 'match($5,/[6-9]d|[0-9][0-9]d|[0-9][0-9][0-9]d/) {print $0}')
</code></pre>
<p>The value can and should be adjusted by modifying the <code>awk</code> scripting in order to match your use case.</p>
