
The PostgreSQL server is one of the most advanced database management systems for creating modern data-driven applications. PostgreSQL supports a complete set of SQL date and time data types (For example, date, time, timestamp, and interval) for storing date and time-related data.
Here are several use cases where you can use the PostgreSQL date data types when working on a database project:
Timestamping new table records with the server's date.
Storing dates of birth for customers, employees, patients, and more.
Calculating the time difference between two dates.
Checking car license or health insurance expiration dates using the PostgreSQL INTERVAL keyword.
This guide shows you how to use the PostgreSQL date data types on Ubuntu 20.04.
To proceed with this guide:
Log in to your Vultr account. Navigate to Products then Databases. Click your managed database under Managed Database Name and find the database Connection Details. This guide uses the following sample connection details:
username: vultradmin
password: EXAMPLE_POSTGRESQL_PASSWORD
host: SAMPLE_POSTGRESQL_DB_HOST_STRING.vultrdb.com
port: 16751
To test the PostgreSQL server date data types, you need a sample database and a table. Follow the steps below to initialize the database:
SSH to your Linux server and install the psql package, a command-line client for managing a PostgreSQL database.
Run the psql command to connect to your managed PostgreSQL cluster. Replace SAMPLE_POSTGRESQL_DB_HOST_STRING.vultrdb.com, 16751, and vultradmin with the correct host, port, and username for your managed PostgreSQL cluster.
Enter your PostgreSQL cluster password and press Enter to proceed.
Create a sample company_db database.
Output.
Connect to the new company_db database.
Output.
Create a customers table. In the customers table, the customer_id column acts as a PRIMARY KEY to uniquely identify records. The SERIAL keyword instructs the PostgreSQL server to automatically assign customer_ids for new records. The first_name and last_name fields use the VARCHAR(50) data type. To store the customers' dates of birth using the YYYY-MM-DD format, use a DATE data type.
Output
Insert sample records into the customers records.
Output.
Query the customers table to ensure the data is in place.
Output.
After setting up the database and the sample table, follow the next step to learn how to use the PostgreSQL TIMESTAMP function.
TIMESTAMP for New RowsPostgreSQL allows you to timestamp records when inserting them into a table. The TIMESTAMP function is crucial when recording the exact time when entering records in a table according to the PostgreSQL server's time. Follow the steps below to insert a new column for timestamping customers' records.
Alter the customers table and add a new created_on column. Then, issue the TIMESTAMP DEFAULT NOW() statement to instruct the PostgreSQL server to timestamp new records depending on the database server's time.
Output.
Insert a new record into the customers table. Don't specify a value for the created_on column. PostgreSQL should now assign a date value automatically.
Output.
Query the customers table again to ensure everything runs as expected.
Verify the output below. As you can see, PostgreSQL automatically assigns a new timestamp for the created_on column.
After learning how to timestamp new table records, the next step focuses on formatting the date outputs to different formats.
The default format for the PostgreSQL timestamps may confuse users, especially when generating reports. Luckily, you can use the PostgreSQL TO_CHAR() function to format date values to human-friendly outputs by following the steps below:
Familiarize yourself with the PostgreSQL TO_CHAR() function. The function takes two arguments. The SAMPLE_INPUT_VALUE_OR_COLUMN is the raw data that you want to format. The SAMPLE_DATE_FORMAT represents the output format. The TO_CHAR() converts a timestamp to a string.
Use the following list to understand some valid timestamp strings.
DD: Day of the month from 01 to 31.
MM: Position of the month in the year from 01 to 12.
MON: Abbreviated month name.
Month: Full capitalized month name.
YYYY: Full four digits of the year.
Implement the above list to format the customers' date of birth using the DD/MMM/YYYY format.
Output.
Repeat the same SQL commands but this time around, use the month name abbreviation format (MON).
Output.
You've formatted a PostgreSQL timestamp to different date formats. Proceed to the next step to learn how to use the AGE function.
AGE FunctionThe PostgreSQL server AGE function allows you to calculate the number of years, months, and days between two different timestamps, as illustrated below.
Run the AGE() function against the customers table to calculate the customers' age based on the PostgreSQL server's date (CURRENT_DATE). The AGE() function is useful in health records applications when finding patients' ages using their dates of birth. Other use cases of the AGE() function include calculating house occupation durations and employees' stay in the company.
Output.
After finding the customers' ages, proceed to the next step and use the NOW() and EXTRACT() functions.
NOW() and EXTRACT() FunctionsThe PostgreSQL NOW() function returns the date and time based on your database server's time zone. You can also use the CURRENT_TIMESTAMP command to get the same results. To retrieve a date subfield, PostgreSQL supports the EXTRACT() function. Follow the steps below to test these functions:
Retrieve the database server's date and time by running the following SQL command.
Output.
Fetch the subfields of a date value in the PostgreSQL server using the EXTRACT function.
Output.
After working with the NOW() and EXTRACT() functions, learn how to use the date interval and timezones in the next step.
The PostgreSQL server allows you to store and manipulate a period between two dates using the INTERVAL statement. Also, the TIMEZONE function allows you to work with database timezones. Run the following examples to implement these functions:
Retrieve the PostgreSQL server's timezone.
Output.
Run the command below to retrieve a list of all supported time zones.
Output.
Press Q to exit the list. Then, Use the SET command to change the timezone for the active database session.
Output.
Run the NOW() function again.
Output.
Use the following INTERVAL statement to compute the timestamp after one year.
Output.
This guide shows you how to use the PostgreSQL date data types on Ubuntu 20.04 server. Use the examples in this guide when working on your next data-driven application to store and compute date values.
For more information on using Vultr's managed databases, follow the links below:
How to Import CSV Data to Vultr Managed Databases for PostgreSQL.
How to Implement PostgreSQL Database Transactions with Python on Ubuntu 20.04.
0 Comments
Be the first to comment and share your perspective with the community.