in reply to Get the date (MySQL style) for X days ago

Or, if you'd rather use POSIX:
my $offset = 65; my $date = strftime "%Y-%m-%d", localtime(time - $offset * 86400);
And if you'd rather have the format for a datetime field:
my $datetime = strftime "%Y-%m-%d %H:%M:%S", localtime(time - $offset * 86400);
In fact, MySQL itself has some date/time functions that do a lot of the formatting for you, so you could use those instead. The FROM_UNIXTIME function takes a Unix timestamp (epoch seconds) and turns it into a MySQL datetime format for you:
my $offset = 65; my $time = $offset * 86400; my $sth = $dbh->prepare_cached(<<SQL); select host from log where stamp > from_unixtime(?) SQL $sth->execute($time);
where "stamp" is a datetime field.

Of course, if what the original poster really wants is a report of records from the last 7 days, all he/she'd have to use is something like this, which lets MySQL do all the work:

my $sth = $dbh->prepare_cached(<<SQL); select host from log where to_days(now()) - to_days(stamp) > ? SQL $sth->execute(7);
where stamp is, again, a datetime field.

And finally, one more way of doing this--this will give you slightly different results than the last query, because the last query is giving you basically anything from the last 7 days; the following will give you anything *within* the last 7 days (a subtle difference):

my $sth = $dbh->prepare_cached(<<SQL); select host from log where stamp > date_sub(now(), interval ? day) SQL $sth->execute(7);

Replies are listed 'Best First'.
Re^2: Get the date (MySQL style) for X days ago
by ikegami (Patriarch) on May 21, 2008 at 20:52 UTC
    Your first three solutions are wrong. You assume that every day has 86400 seconds.
    use POSIX qw( strftime ); use Time::Local qw( timelocal ); # Pretend we're executing at 12:00:05 am on Mar 12th, 2008. # The DST time zone change occured on Mar 9th, 2008 here. my $time = timelocal(5,0,0,12,3-1,2008); my $offset = 7; my $date = strftime "%Y-%m-%d", localtime($time - $offset * 86400); print("Expecting: 2008-03-05\n"); print("Received: $date\n");
    Expecting: 2008-03-05 Received: 2008-03-04

    See Re: Get the date (MySQL style) for X days ago for a solution.