69

Suppose I do this in redis at 13:30 20 Feb 2020,

> set foo "bar spam"
OK

I want to get time of creation of foo. Is there something like

> gettime foo
13:30 20 Feb 2020

?

Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146

3 Answers3

99

Redis doesn't store this information.

You could use a separate key:

MULTI
SET foo "bar spam"
SET foo:time "13:30 20 Feb 2020"
EXEC

GET foo:time
Donald Miner
  • 38,889
  • 8
  • 95
  • 118
18

There is another, similar option to solve this, for the use case when you need timer to detect expired value without deleting the value itself:

MULTI
SET foo "bar"
SET foo:alive 1 EX 30
EXEC

Here 30 - is a desired timeout. You can then determine whether value is still "alive" with:

EXISTS foo:alive
Damaged Organic
  • 8,175
  • 6
  • 58
  • 84
7

I think it's possible if you know initial TTL;

you can do like this:

$init = 60; //initial time
$ttl = $redis->ttl("key"); //current ttl
$diff = $init - $ttl; //difference is the time passed after key was created
$creation = time() - $diff; //this is creation time in seconds since unix epoch
legale
  • 612
  • 7
  • 9
  • I think this is a good workaround to store the creation time in Redis, but if you don't want your key to expire make sure you set it to a very long expiration that it will never happen, like 30 years (946080000) – Rodrigo Estebanez Mar 10 '21 at 17:50