Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Now() without timezone

I have a column added_at of type timestamp without time zone. I want it's default value to be the current date-time but without time zone. The function now() returns a timezone as well.

How do I solve that problem?

like image 353
Incerteza Avatar asked Dec 28 '13 07:12

Incerteza


People also ask

How do you do a timestamp without the time zone?

There is no time zone information being stored in a timestamptz , but instead it is converted to UTC for storage. I'd say, always use timestamptz when the timestamps in question denote absolute time. That's all what timestamptz means.

Is Postgres now () in UTC?

PostgreSQL stores the timestamptz in UTC value.

Is datetime stored without timezone?

DATETIME is a date/time that does not store timezone.

What is now () in PostgreSQL?

The PostgreSQL now function returns the current date and time with the time zone.


2 Answers

SELECT now()::timestamp; 

The cast converts the timestamptz returned by now() to the corresponding timestamp in your time zone - defined by the timezone setting of the session. That's also how the standard SQL function LOCALTIMESTAMP is implemented in Postgres.

If you don't operate in multiple time zones, that works just fine. Else switch to timestamptz for added_at. The difference?

  • Ignoring time zones altogether in Rails and PostgreSQL

BTW, this does exactly the same, just more noisy and expensive:

SELECT now() AT TIME ZONE current_setting('timezone'); 
like image 198
Erwin Brandstetter Avatar answered Sep 25 '22 04:09

Erwin Brandstetter


Well you can do something like:

SELECT now() AT TIME ZONE current_setting('TimeZone'); SELECT now() AT TIME ZONE 'Europe/Paris'; SELECT now() AT TIME ZONE 'UTC'; 

Not sure how that makes any sense for a column "added_at". You almost always want an absolute timestamp (timestamp with time zone) not a floating one.


Edit responding to points below:

  1. Yes, should use timestamp with time zone (absolute time) unless you have a good reason not to.

  2. The client timezone is given by SHOW TimeZone or current_setting(...) as shown above.

Do take some time to skim the manuals - they cover all this quite well.

like image 32
Richard Huxton Avatar answered Sep 26 '22 04:09

Richard Huxton