Re: subtract a day from the NOW function

From: Steve Crawford <scrawford(at)pinpointresearch(dot)com>
To: Scott Marlowe <smarlowe(at)g2switchworks(dot)com>
Cc: "Campbell, Lance" <lance(at)uiuc(dot)edu>, Michael Glaesemann <grzm(at)seespotcode(dot)net>, pgsql-sql(at)postgresql(dot)org
Subject: Re: subtract a day from the NOW function
Date: 2007-06-07 18:58:38
Message-ID: 4668555E.20003@pinpointresearch.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

Scott Marlowe wrote:
> Campbell, Lance wrote:
>> Michael,
>> So based on your feedback would it be better to do option A or B below?
>>
>> 1) I have a timestamp field, "some_timestamp", in table "some_table".
>> 2) I want to compare field "some_timestamp" to the current date - 1 day.
>> I need to ignore hours, minutes and seconds.
>>
> You might want to use date_trunc then:
>
> select * from sometable where date_trunc('day',tiemstampfield) >
> date_trunc('day',now() - interval '1 day');
>
> or something like that.

Beware in the "or something like that category" that PostgreSQL
considers "1 day" to be "24 hours" thus depending on whether the
timestampfield is with or without TZ and where you do your truncation
(before or after subtracting), you can end up with unexpected results in
the vicinity of DST changes:

select '2007-03-12'::timestamptz - '1 day'::interval;
?column?
------------------------
2007-03-10 23:00:00-08

select '2007-03-12'::timestamp - '1 day'::interval;
?column?
---------------------
2007-03-11 00:00:00

Especially note that truncating a timestamptz preserves the timezone
info so you will very likely need to address issues on the days that
Daylight Saving starts or ends:

select date_trunc('day',current_timestamp);
date_trunc
------------------------
2007-06-07 00:00:00-07

Cheers,
Steve

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Guy Fraser 2007-06-07 19:20:43 Re: Creditcard Number Security was Re: Encrypted column
Previous Message Robert Fitzpatrick 2007-06-07 18:46:46 Generate random password

Browse pgsql-sql by date

  From Date Subject
Next Message Michael Glaesemann 2007-06-07 19:22:44 Re: subtract a day from the NOW function
Previous Message Michael Glaesemann 2007-06-07 18:22:05 Re: subtract a day from the NOW function