The Redis PEXPIRETIME
command returns the absolute Unix timestamp in milliseconds at which the given key will expire. This is the number of milliseconds since 00:00:00 UTC on 1 January 1970 until the expiry time of the key.
This works exactly the same as EXPIRETIME
, but it returns the Unix timestamp in milliseconds instead of seconds.
The PEXPIRETIME
command was introduced in Redis 7.0.0.
Syntax
The syntax goes like this:
PEXPIRETIME key
Where key
is the key for which to get the expiry time.
Example
Suppose we set a key with an expiry:
SET dinner "Pasta" PX 86400000
Result:
OK
Here, I used the PX
argument of the SET
command to set an expiry in milliseconds. I could have alternatively used the EX
argument to set it in milliseconds. Either way, it wouldn’t change the results we get with PEXPIRETIME
(assuming the same expiry time).
Another way to do it would be with the EXPIRE
or EXPIREAT
commands (for seconds), or with the PEXPIRE
or PEXPIREAT
commands (for milliseconds).
Anyway, we can now use the PEXPIRETIME
command to check that key’s expiry time in Unix time:
PEXPIRETIME dinner
Result:
(integer) 1655949518046
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:
PEXPIRETIME dinner
Result:
(integer) 1655949518046
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 PTTL
command against it to check its time to live in milliseconds:
PTTL dinner
Result:
(integer) 86324550
We get an integer reply with the current time to live (in milliseconds). 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):
PTTL dinner
Result:
(integer) 86302301
This is in contrast to the absolute Unix timestamp of the expiry.
There’s also a TTL
command that returns the time to live in seconds.
Keys Without an Expiry
If the key has no expiry, PEXPIRETIME
returns an integer reply of -1
.
To test this, let’s remove the expiry of our key:
PERSIST dinner
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 PEXPIRETIME
against that key:
PEXPIRETIME dinner
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, PEXPIRETIME
returns an integer reply of -2
.
Let’s delete our key:
DEL dinner
Result:
(integer) 1
The key has been deleted.
And now let’s try to run PEXPIRETIME
against the deleted key:
PEXPIRETIME dinner
Result:
(integer) -2
As expected, an integer reply of -2
.