Redis EXPIRETIME Command Explained

The Redis EXPIRETIME command returns the absolute Unix timestamp in seconds at which the given key will expire. This is the number of seconds since 00:00:00 UTC on 1 January 1970 until the expiry time of the key.

The EXPIRETIME command was introduced in Redis 7.0.0.

Syntax

The syntax goes like this:

EXPIRETIME key

Where key is the key for which to get the expiry time.

Example

Suppose we set a key with an expiry:

SET lunch "Chicken Salad" EX 86400

Result:

OK

We can now use the EXPIRETIME command to check that key’s expiry time in Unix time:

EXPIRETIME lunch

Result:

(integer) 1655886492

This is the absolute Unix timestamp of the key’s expiry. If we run the statement again at a later time, we get exactly the same result:

EXPIRETIME lunch

Result:

(integer) 1655886492

The absolute Unix timestamp of the key’s expiry is not to be confused with the current time to live (TTL) of the key.

Let’s run the TTL command against it to check its TTL:

TTL lunch

Result:

(integer) 86214

We get an integer reply with the current time to live. If we run the same command again, we get a different result, due to the expiry getting nearer (and therefore, the time to live getting shorter):

TTL lunch

Result:

(integer) 86136

This is in contrast to the absolute Unix timestamp of the expiry.

Keys Without an Expiry

If the key has no expiry, EXPIRETIME returns an integer reply of -1.

To test this, let’s remove the expiry of our key:

PERSIST lunch

Result:

(integer) 1

The PERSIST command removes any timeout on the given key. We got an integer reply of 1, which means that it successfully removed the timeout on our key.

Now let’s run EXPIRETIME against that key:

EXPIRETIME lunch

Result:

(integer) -1

As expected, we get an integer reply of -1, which means that the key doesn’t have an expiry set.

Non-Existent Keys

If the key doesn’t exist, EXPIRETIME returns an integer reply of -2.

Let’s delete our key:

DEL lunch

Result:

(integer) 1

The key has been deleted.

And now let’s try to run EXPIRETIME against the deleted key:

EXPIRETIME lunch

Result:

(integer) -2

As expected, an integer reply of -2.

There’s also a PEXPIRETIME command that does the same thing as EXPIRETIME, except that it returns the result in milliseconds.