Postgres: Update date and retain time from timestamp - postgresql

I have a field1 with timestamp, datatype and values format is 2016-02-23 12:01:30.
I'm running the query:
UPDATE <table> set field1 = '2015-12-31'::timestamp::date where .....
The output changes to:
2015-12-31 00:00:00
It converts the time to all zero's. How to change the date and retain the timestamp?

Try this:
UPDATE mytable
SET field1 = '2015-12-31'::timestamp +
EXTRACT(HOUR FROM field1) * INTERVAL '1 HOUR' +
EXTRACT(MINUTE FROM field1) * INTERVAL '1 MINUTE' +
EXTRACT(SECOND FROM field1) * INTERVAL '1 SECOND'
WHERE ...
Demo here

There's another way, using the DateTime type.
So if you want to set a table's Date to today, you can use this:
UPDATE table SET column = current_date::date + column::time;
Switch current_date with "2019-02-23" and it should work as well.

Simply add the new date and the existing time. Here it is:
UPDATE mytable
SET field1 = '2015-12-31'::date + field1::time with time zone
WHERE ...;
or even cleaner cut:
UPDATE mytable
SET field1 = field1 - field1::date + '2015-12-31'::date
WHERE ...;

The subtraction of timestamps yields an interval. The resulting interval is can the be added to the desired date to give the desired date with the prior time.
with ats (old_tz) as (select now() )
select old_tz, '2015-12-31'::timestamptz + (old_tz - date_trunc('day', old_tz)) new_tz
from ats;
OOPS. Didn't realize how old this post was until after posting, but still believe it may valuable to future viewers. So I'll just leave it.

Related

Postgres query timestamp by datepart only

I'm using this to try and get all events with a timestamp of today
SELECT systemuserid,ondate from auditlog
WHERE ondate::date = NOW()::date
Performance seems really bad, over 2 minutes. I have a index on ondate.
Is there a more efficient way to do it?
Thanks
Use a range condition:
select *
from auditlog
where ondate >= current_date
and ondate < current_date + 1;
current_date will be converted to a timestamp at midnight, so ondate => current_date will include everything from "today".
And the condition ondate < current_date + 1 will exclude rows with a timestamp of tomorrow (midnight) or later.

Add an interval day to a date from postgresql

I would like to add a day to a date from postgreSQL, so i tried this one :
SELECT * FROM t_ask a
WHERE ask_datesend is null
AND a.ask_date_reception >= ('2019-06-12' + INTERVAL '1 day');
But it doesn't work.
But if i try that i have an answer :
SELECT * FROM t_ask a
WHERE ask_datesend is null
AND a.ask_date_reception >= '2019-06-12'
Little precision in a.ask_date_reception the date is like
"2019-06-12 15:28:01.982"
Try an explicit conversion:
a.ask_date_reception >= ('2019-06-12'::date + INTERVAL '1 day');
Or use timestamp or timestamp with time zone instead of date.

How define today date with Default timestmp

I am using postgressql i wish to get the data for currentdate, i want filter the data based on the date
in data base my plandate filed is define as Time stamp with time zone so its showing like this format 2013-09-01 03:22:01.438348+05:30 my query is like this
select ttodoid ,date,details from ttodo where date=currentdate():
but currentdate function giving me just date '2013-10-06' based on this result is no rows how can i manage it for today date detail
UPDATED: One way to do it
SELECT *
FROM ttodo
WHERE date BETWEEN DATE_TRUNC('day', CURRENT_TIMESTAMP)
AND DATE_TRUNC('day', CURRENT_TIMESTAMP)
+ INTERVAL '1 DAY'
- INTERVAL '1 MICROSECOND';
or
SELECT *
FROM ttodo
WHERE date >= DATE_TRUNC('day', CURRENT_TIMESTAMP)
AND date < DATE_TRUNC('day', CURRENT_TIMESTAMP)
+ INTERVAL '1 DAY';
Here is SQLFiddle demo
select * from ttodo where (ttodo.todoplandate::date = current_date) or
(ttodo.todoplandate::date < current_date
I think the easier approach would be just to convert your field to date:
SELECT ttodoid ,date,details FROM ttodo
WHERE CAST(date AS DATE) = current_date;
Notice that, ff you want this query to be indexed, you have to create the index with the cast:
CREATE INDEX idx_ttodo_date ON ttodo ((CAST(date AS DATE)));
Another approach, is instead of casting the field, is checking the intervals, something similar of what petern proposed, but with correct intervals:
SELECT ttodoid ,date,details FROM ttodo
WHERE date >= date_trunc('day', current_timestamp)
AND date < (date_trunc('day', current_timestamp) + interval '1day');
This approach has the advantage that it can use an index on the date field only, which is good if you already have it.

select dates between two unix timestamps

I have the table users.
Columns:
user_id - integer
user_date - integer(unix timestamp)
Some of rows have user_date and some have NULL.
I need to find all user_id's which user_date includes period between '2012-10-21' and '2012-10-24'
SELECT *
FROM users
WHERE user_date BETWEEN
EXTRACT(EPOCH FROM date '2012-10-21') AND
EXTRACT(EPOCH FROM date '2012-10-24' + interval '1 day');
If you don't want the end date to be included, remove the bit adding a day to that.
select *
from users
where
timestamp 'epoch' + user_date * interval '1 second' between '2012-10-21' and '2012-10-24'
and
user_date is not null

Postgres birthdays selection

I work with a Postgres database. This DB has a table with users, who have a birthdate (date field). Now I want to get all users who have their birthday in the upcoming week....
My first attempt: SELECT id FROM public.users WHERE id IN (lange reeks) AND birthdate > NOW() AND birthdate < NOW() + interval '1 week'
But this does not result, obviously because off the year. How can I work around this problem?
And does anyone know what happen to PG would go with the cases at 29-02 birthday?
We can use a postgres function to do this in a really nice way.
Assuming we have a table people, with a date of birth in the column dob, which is a date, we can create a function that will allow us to index this column ignoring the year. (Thanks to Zoltán Böszörményi):
CREATE OR REPLACE FUNCTION indexable_month_day(date) RETURNS TEXT as $BODY$
SELECT to_char($1, 'MM-DD');
$BODY$ language 'sql' IMMUTABLE STRICT;
CREATE INDEX person_birthday_idx ON people (indexable_month_day(dob));
Now, we need to query against the table, and the index. For instance, to get everyone who has a birthday in April of any year:
SELECT * FROM people
WHERE
indexable_month_day(dob) >= '04-01'
AND
indexable_month_day(dob) < '05-01';
There is one gotcha: if our start/finish period crosses over a year boundary, we need to change the query:
SELECT * FROM people
WHERE
indexable_month_day(dob) >= '12-29'
OR
indexable_month_day(dob) < '01-04';
To make sure we match leap-day birthdays, we need to know if we will 'move' them a day forward or backwards. In my case, it was simpler to just match on both days, so my general query looks like:
SELECT * FROM people
WHERE
indexable_month_day(dob) > '%(start)%'
%(AND|OR)%
indexable_month_day(dob) < '%(finish)%';
I have a django queryset method that makes this all much simpler:
def birthday_between(self, start, finish):
"""Return the members of this queryset whose birthdays
lie on or between start and finish."""
start = start - datetime.timedelta(1)
finish = finish + datetime.timedelta(1)
return self.extra(where=["indexable_month_day(dob) < '%(finish)s' %(andor)s indexable_month_day(dob) > %(start)s" % {
'start': start.strftime('%m-%d'),
'finish': finish.strftime('%m-%d'),
'andor': 'and if start.year == finish.year else 'or'
}]
def birthday_on(self, date):
return self.birthday_between(date, date)
Now, I can do things like:
Person.objects.birthday_on(datetime.date.today())
Matching leap-day birthdays only on the day before, or only the day after is also possible: you just need to change the SQL test to a `>=' or '<=', and not adjust the start/finish in the python function.
I'm not overly confident in this, but it seems to work in my testing. The key here is the OVERLAPS operator, and some date arithmetic.
I assume you have a table:
create temporary table birthdays (name varchar, bday date);
Then I put some stuff into it:
insert into birthdays (name, bday) values
('Aug 24', '1981-08-24'), ('Aug 04', '1982-08-04'), ('Oct 10', '1980-10-10');
This query will give me the people with birthdays in the next week:
select * from
(select *, bday + date_trunc('year', age(bday)) + interval '1 year' as anniversary from birthdays) bd
where
(current_date, current_date + interval '1 week') overlaps (anniversary, anniversary)
The date_trunc truncates the date at the year, so it should get you up to the current year. I wound up having to add one year. This suggests to me I have an off-by-one in there for some reason. Perhaps I just need to find a way to get dates to round up. In any case, there are other ways to do this calculation. age gives you the interval from the date or timestamp to today. I'm trying to add the years between the birthday and today to get a date in the current year.
The real key is using overlaps to find records whose dates overlap. I use the anniversary date twice to get a point-in-time.
Finally, to show the upcoming birthdays of the next 14 days I used this:
SELECT
-- 14 days before birthday of 2000
to_char( to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') - interval '14 days' , 'YYYY-MM-dd') as _14b_b2000,
-- birthday of 2000
to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') as date_b2000,
-- current date of 2000
to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') as date_c2000,
-- 14 days after current date of 2000
to_char( to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') + interval '14 days' , 'YYYY-MM-dd') as _14a_c2000,
-- 1 year after birthday of 2000
to_char( to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') + interval '1 year' , 'YYYY-MM-dd') as _1ya_b2000
FROM c
WHERE
-- the condition
-- current date of 2000 between 14 days before birthday of 2000 and birthday of 2000
to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') between
to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') - interval '14 days' and
to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd')
or
-- 1 year after birthday of 2000 between current date of 2000 and 14 days after current date of 2000
to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') + interval '1 year' between
to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') and
to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') + interval '14 days'
;
So:
To solve the leap-year issue, I set both birthdate and current date to 2000,
and handle intervals only from this initial correct dates.
To take care of the near end/beginning dates,
I compared first the 2000 current date to the 2000 birthday interval,
and in case current date is at the end of the year, and the birthday is at the beginning,
I compared the 2001 birthday to the 2000 current date interval.
Here's a query that gets the right result, most of the time.
SELECT
(EXTRACT(MONTH FROM DATE '1980-08-05'),
EXTRACT(DAY FROM DATE '1980-08-05'))
IN (
SELECT EXTRACT(MONTH FROM CURRENT_DATE + s.a) AS m,
EXTRACT(DAY FROM CURRENT_DATE + s.a) AS d
FROM GENERATE_SERIES(0, 6) AS s(a)
);
(it doesn't take care of leap years correctly; but you could use extract again to work the subselect in terms of a leap year instead of the current year.
EDIT: Got it working for all cases, and as a useful query rather than a scalar select. I'm using some extra subselects so that I don't have to type the same date or expression twice for month and day, and of course the actual data would be in a table instead of the values expression. You might adapt this differently. It might still stand to improve by making a more intelligent series for weeks containing leap days, since sometimes that interval will only contain 6 days (for non-leap years).
I'll try to explain this from the inside-out; First thing I do is normalize the target date (CURRENT_DATE usually, but explicit in this code) into a year that I know is a leap year, so that February 29th appears among dates. The next step is to generate a relation with all of the month-day pairs that are under consideration; Since there's no easy way to do an interval check in terms of month-day, it's all happening using generate_series,
From there it's a simple matter of extracting the month and day from the target relation (the people alias) and filtering just the rows that are in the subselect.
SELECT *
FROM
(select column1 as birthdate, column2 as name
from (values
(date '1982-08-05', 'Alice'),
(date '1976-02-29', 'Bob'),
(date '1980-06-10', 'Carol'),
(date '1992-06-13', 'David')
) as birthdays) as people
WHERE
((EXTRACT(MONTH FROM people.birthdate),
EXTRACT(DAY FROM people.birthdate)) IN (
SELECT EXTRACT(MONTH FROM thedate.theday + s.a) AS m,
EXTRACT(DAY FROM thedate.theday + s.a) AS d
FROM
(SELECT date (v.column1 -
(extract (YEAR FROM v.column1)-2000) * INTERVAL '1 year'
) as theday
FROM (VALUES (date '2011-06-09')) as v) as thedate,
GENERATE_SERIES(0, 6) AS s(a)
)
)
Operating on days, as I've done here, should work splendidly all the way up until a two month interval (if you wanted to look out that far), since december 31 + two months and change should include the leap day. On the other hand, it's almost certainly more useful to just work on whole months for such a query, in which case you don't really need anything more than extract(month from ....
First find out how old the person currently is using age(), then grab the year from that extract(year from age()). This is how old they are currently in years, so for their age at their next birthday add 1 to the year. Then their next birthday is found by adding an interval of this many years * interval '1 year' to their birthday. Done.
I've used a subselect here to add the next_birth_day column in to the complete table to make the select clause simpler. You can then play with the where conditions to suit your needs.
select *
from (
select *,
(extract(year from age(birth_date)) + 1) * interval '1 year' + birth_date "next_birth_day"
from public.users
) as users_with_upcoming_birth_days
where next_birth_day between now() and now() + '7 days'
This is based on Daniel Lyons's anniversary idea, by calculating the interval between the next birthday and today, with just +/- date arithmetic:
SELECT
today,
birthday,
CASE
WHEN this_year_anniversary >= today
THEN this_year_anniversary
ELSE this_year_anniversary + '1 year'::interval
END - today < '1 week'::interval AS is_upcoming
FROM
(
SELECT
today,
birthday,
birthday + years AS this_year_anniversary
FROM
(
SELECT
today,
birthday,
((
extract(year FROM today) - extract(year from birthday)
) || ' years')::interval AS years
FROM
(VALUES ('2011-02-28'::date)) AS t1 (today),
(VALUES
('1975-02-28'::date),
('1975-03-06'::date),
('1976-02-28'::date),
('1976-02-29'::date),
('1976-03-06'::date)
) AS t2 (birthday)
) AS t
) AS t;
In case you want it to work with leap years:
create or replace function birthdate(date)
  returns date
as $$
  select (date_trunc('year', now()::date)
         + age($1, 'epoch'::date)
         - (extract(year from age($1, 'epoch'::date)) || ' years')::interval
         )::date;
$$ language sql stable strict;
Then:
where birthdate(birthdate) between current_date
and current_date + interval '1 week'
See also:
Getting all entries who's Birthday is today in PostgreSQL
Exemple: birthdate between: jan 20 and feb 10
SELECT * FROM users WHERE TO_CHAR(birthdate, '1800-MM-DD') BETWEEN '1800-01-20' AND '1800-02-10'
Why 1800?
No matter may be any year;
In my registration form, I can inform the date of birth (with years) or just the birthday (without year), in which case I saved as 1800 to make it easier to work with the date
Here's my take, which works with leap years too:
CREATE OR REPLACE FUNCTION days_until_birthday(
p_date date
) RETURNS integer AS $$
DECLARE
v_now date;
v_days integer;
v_date_upcoming date;
v_years integer;
BEGIN
v_now = now()::date;
IF (p_date IS NULL OR p_date > v_now) THEN
RETURN NULL;
END IF;
v_years = date_part('year', v_now) - date_part('year', p_date);
v_date_upcoming = p_date + v_years * interval '1 year';
IF (v_date_upcoming < v_now) THEN
v_date_upcoming = v_date_upcoming + interval '1 year';
END IF;
v_days = v_date_upcoming - v_now;
RETURN v_days;
END
$$ LANGUAGE plpgsql IMMUTABLE;
I know this post is old, but I had the same issue and came up with this simple and elegant solution:
It is pretty easy with age() and accounts for lap years... for the people who had their birthdays in the last 20 days:
SELECT * FROM c
WHERE date_trunc('year', age(birthdate)) != date_trunc('year', age(birthdate + interval '20 days'))
I have simply created this year date from original birth date.
( DATE_PART('month', birth_date) || '/' || DATE_PART('day', birth_date) || '/' || DATE_PART('year', now()))::date between :start_date and :end_date
I hope this help.