Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Tuesday, 6 February 2024

PostgreSQL Date and Time Functions

PostgreSQL provides a comprehensive set of date and time functions for manipulating date and time values, performing date arithmetic, and formatting dates and times. Here's an overview of some commonly used PostgreSQL date and time functions:


 1. Current Date and Time:


- CURRENT_DATE: Returns the current date.

  

  SELECT CURRENT_DATE;

  


- CURRENT_TIME: Returns the current time (without timezone).

  

  SELECT CURRENT_TIME;

  


- CURRENT_TIMESTAMP: Returns the current timestamp (with timezone).

  

  SELECT CURRENT_TIMESTAMP;

  


 2. Extracting Date and Time Components:


- EXTRACT: Extracts the specified field from a timestamp.

  

  SELECT EXTRACT(YEAR FROM timestamp_column) AS year;

  


 3. Date Arithmetic:


- DATE_PART: Returns a part of a date or time (similar to EXTRACT).

  

  SELECT DATE_PART('hour', timestamp_column) AS hour;

  


- AGE: Calculates the difference between two dates or timestamps.

  

  SELECT AGE(timestamp_column1, timestamp_column2) AS age;

  


- INTERVAL: Represents a time span, used for date arithmetic.

  

  SELECT CURRENT_DATE + INTERVAL '1 month';

  


 4. Date Formatting:


- TO_CHAR: Converts a date or timestamp to a character string with a specified format.

  

  SELECT TO_CHAR(timestamp_column, 'YYYY-MM-DD HH24:MI:SS') AS formatted_date;

  


 5. Date Truncation:


- DATE_TRUNC: Truncates a date or timestamp to the specified precision.

  

  SELECT DATE_TRUNC('month', timestamp_column) AS truncated_date;

  


 6. Time Zone Conversion:


- AT TIME ZONE: Converts a timestamp from one time zone to another.

  

  SELECT timestamp_column AT TIME ZONE 'UTC' AS utc_timestamp;

  


 7. Generating Date Ranges:


- GENERATE_SERIES: Generates a series of dates or timestamps within a specified range.

  

  SELECT * FROM GENERATE_SERIES('2022-01-01'::date, '2022-12-31'::date, '1 month');

  


 8. Time Interval Functions:


- MAKE_INTERVAL: Constructs an interval from specified components.

  

  SELECT MAKE_INTERVAL(days := 1, hours := 12);

  


PostgreSQL date and time functions provide a rich set of capabilities for working with date and time values in SQL queries. Whether you need to extract date components, perform date arithmetic, format dates, or convert time zones, PostgreSQL offers a wide range of functions to suit your requirements. Experiment with these functions to manipulate and analyze date and time data effectively in PostgreSQL.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.