Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timezone aware date_trunc function

Tags:

The following query

SELECT the_date FROM date_trunc('day', timestamp with time zone         '2001-01-1 00:00:00+0100') as the_date 

results to

the_date 2000-12-31 00:00 

Is there a way to tell date_trunc to do day/month/year conversions based on the timezone it is feeded with?

The expected output would be: 2001-01-1 00:00+0100

like image 678
Jay Avatar asked Jun 04 '14 14:06

Jay


People also ask

How to check if a DateTime object is timezone aware or not?

An aware object represents a specific moment in time that is not open to interpretation. We can easily check if a datetime object is timezone-aware or not. For this, we will store the current date and time in a new variable using the datetime.now () function of datetime module.

Why does date_trunc return a timestamp with no timezone?

The important thing to understand is date_trunc returns a timestamp with no timezone attached to it. You need to convert the timestamp to the proper timezone because the database client or whatever downstream might have a different timezone. Show activity on this post. @Adam's answer is definitely more helpful.

What does timezone aware mean in Python?

Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is timezone aware or not: We can easily check if a datetime object is timezone-aware or not.

What is the returned value when I truncate a time?

Note that in all cases, the returned value is a TIMESTAMP , but with zeroes for the portions (e.g. fractional seconds) that were truncated: Truncate a time down to the minute:


2 Answers

You need to specify at which time zone you want it to show

select     date_trunc(         'day',         timestamp with time zone '2001-01-1 00:00:00+0100' at time zone '-02'     ) as the_date;       the_date        ---------------------  2001-01-01 00:00:00 

AT TIME ZONE

like image 66
Clodoaldo Neto Avatar answered Jan 09 '23 17:01

Clodoaldo Neto


While the marked answer might be correct for the OP's weird circumstances it is more likely incorrect for others. You need to convert the timestamp returned by date_trunc to the proper timezone.

select     date_trunc(         'day',         some_timestamp at time zone users_timezone     ) at time zone users_timezone as the_date; 

The important thing to understand is date_trunc returns a timestamp with no timezone attached to it. You need to convert the timestamp to the proper timezone because the database client or whatever downstream might have a different timezone.

like image 28
Adam Gent Avatar answered Jan 09 '23 16:01

Adam Gent