EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Datetime
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL Datetime

By Payal UdhaniPayal Udhani

PostgreSQL Datetime

Introduction to PostgreSQL Datetime

In every database, some data types help to store and manipulate values related to date and time or both togetherly. In PostgreSQL too, we have 6 different data types that are present to store and manipulate dates and time in the database. Many functions help us to retrieve and manage them properly and efficiently as per use-case requirements and purposes. In this article, we will learn about the datatypes and syntaxes and examples of some of the most frequently used data and time-related functions that are used in PostgreSQL and discuss the timestamps and time zones. In this topic, we are going to learn about PostgreSQL Datetime.

Datatypes for storing date and time

Data Type Size of storage Description
timestamp 8  bytes Used to store the date and time togetherly
timestamptz 8  bytes Used to store date and time along with the timezone consideration
interval 12  bytes Used to store the time intervalin database
date 4  bytes Only stores date value in the datatbase
time 8  bytes It is used to store only time value in datatbase
timetz 12  bytes Time can be stored along with zone consideration in database

Timestamp allows us to store the date as well as time. In the case of timestamptz data typed values the time zone is also considered and the value is stored in the UTC format. Whenever we try to store any value in the timestamptz datatype value then it is automatically converted into its corresponding UTC value and then its UTC value is stored in the database table. Whenever this value is tried to fetch the PostgreSQL database server retrieves the UTC value from the table and then that value is converted into an appropriate time zone set which is generally set in the database server or by the user whichever is the time zone of the current database connection. The same is the case with the storage of time and timetz.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Functions

There are many functions available for the date and time manipulation.

Function Name Description
Age(timestamp[,timestamp]) To get the difference between a particular timestamp and current timestamp or difference between two timestamps in the form of years, months and days.
CURRENT_DATE It is used to get the current date according to the database’s timezone and settings.
CURRENT_TIME It is used to get the current date according to the database’s timezone and settings.
DATE_PART(field,source) It is used to get particular value from the date, for example, a year or just month or whichever field value from the source timestamp or interval.
EXTRACT(field FROM source) It is similar to date_part and is used to retrieve the value of a particular field from the given timestamp or interval whichever source is specified.
ISFINITE(date|timestamp|interval) It is used to test whether the supplied value that can be either timestamp, interval or date is finite or infinite.
JUSTIFY(interval) It is used to retrieve data in years, months, days and time formats and adjust the interval.

Examples of PostgreSQL Datetime

To understand working more clearly, let us consider one example. We will prepare one table with two columns one with the timestamp and another with timestamptz. Check the current timezone and insert one record in the above table and check its value. And then change the time zone of the database server and check the outputs. Let us first list out all available databases and then switch o database named educational_platform by using \list and then \c educational_platform.

\list

Postgresql Datetime output 1

Let us check all the tables in it with the help of \dt command and then create one table named establish_timestamp in the following way.

CREATE TABLE establish_timestamp (timestampCol TIMESTAMP, timestamptzC0l TIMESTAMPTZ);

Postgresql Datetime output 2

let us check out the current timezone with the help of SHOW TIMEZONE command.

SHOW TIMEZONE;

Postgresql Datetime output 3

As can be seen, the current timezone is Asia/Kolkata. To get the current timestamp we can use the command SELECT NOW() which gives the output as follows.

SELECT NOW();

Postgresql Datetime output 4

Now let us insert a record in our table establish_timestamp with the same values in both columns using

INSERT INTO establish_timestamp (timestampCol, timestamptzCol) VALUES('2020-03-27 18:10:57','2020-03-27 18:10:57');

and check whether the value is inserted with the help of command

SELECT * FROM establish_timestamp;

Postgresql Datetime output 5

Let us change our time zone to America/New_York using the command

SET timezone = 'America/New_York';

and verify current timezone by the command

SHOW TIMEZONE;

output 6

As can be seen from the output our timezone is changed successfully. Now its time to retrieve the values from our table  establish_timestamp and see what both the columns show using the command

SELECT * FROM establish_timestamp;

output 7

It can be easily seen that both columns show different values. The column timestamptzcol shows the changed value according to America’s timezone while timestampcol shows Kolkata’s timezone value which is unchanged as it was stored. Don’t forget to reset the timezone;)!

Date and Time-related Functions

We will first try to retrieve current date and time using the CURRENT_DATE and CURRENT_TIME functions using the following query statements –

SELECT  CURRENT_DATE;

that results in

output 8

SELECT CURRENT_TIME;

that gives output –

output 9

Consider a particular date, for example, “1996-01-26” is the birth date of someone. We have to find out how old is that person. Then we will use the following query statement to find the same.

SELECT AGE('1996-01-26');

whose output is as follows –

output 10

So that person is 24 years 2 months and 12 days old.

Let us find how old was that person on the 1st of June 2019 i.e ‘2019-06-01’. Then we can find out the result using the following query statement –

SELECT AGE('2019-06-01','1996-01-26');

output 11

So he/she was 23 years 4 months and 6 days old on the 1st of June 2019 if the birth date is 26th of January 1996. Note that the first parameter should always be the greater value that is a recent date and the second one should be older and smaller value. If not mentioned so then the result will be negative. Let us confirm the case by just swiping the first and second parameters –

SELECT AGE('1996-01-26', '2019-06-01');

whose output is as follows –

output 12

Let us find the month in the timestamp using date_part() function using the following query statement –

SELECT date_part('month', TIMESTAMP '2020-04-10 20:38:40');

that results in the following output –

output 13

Let us retrieve the century of the same timestamp –

SELECT EXTRACT(CENTURY FROM TIMESTAMP '2020-04-10 20:38:40');

whose output is as follows –

output 14

So the timestamp belongs to the 21st century.

Let us test whether the timestamp used above is finite or not using isfinite() function –

SELECT isfinite(date '2020-04-10 20:38:40');

that results in

output 15

t stands for true. Hence the timestamp holds finite value.

Let us justify 85 hours in years, months, days and time format.

SELECT justify_hours(interval '85 hours');

that results in –

output 16

Hence, 85 hours are equivalent to 3 days and 13 hours.

Conclusion

PostgreSQL provides us with great temporal datatypes and functions which can be used easily and effectively to reduce our efforts while working with date, time and timestamps in databases. We should try using them frequently.

Recommended Articles

This is a guide to PostgreSQL Datetime. Here we discuss the examples of PostgreSQL Datetime along with the Date and Time-related Functions. You may also have a look at the following articles to learn more –

  1. PostgreSQL JSON
  2. PostgreSQL Timestamp
  3. PostgreSQL LIMIT
  4. PostgreSQL IN Operator
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more