PostgreSQL TO_TIMESTAMP() Function
Last Updated :
26 Sep, 2024
In PostgreSQL, managing and manipulating date and time values is important, especially when they are stored as strings. The to_timestamp
function allows us to convert textual representations of dates and times into a valid timestamp format and making it easier to work with them in queries, calculations or comparisons.
In this article, we'll explore the to_timestamp
function in PostgreSQL, its syntax, common format patterns and practical examples.
PostgreSQL TO_TIMESTAMP() Function
- The
to_timestamp
function in PostgreSQL is used to convert a string or numeric value into a timestamp data type.
- This function is especially useful when dealing with date and time information in formats that need to be transformed into a PostgreSQL timestamp for further operations or storage.
Syntax:
to_timestamp(string text, format text) → timestamp
Explanation:
string
: The input value that needs to be converted to a timestamp. It can be a string representing a date and time or a numeric value.
format
: A string that specifies the format of the input string or number. This format helps PostgreSQL understand how the input value should be parsed and converted into a timestamp.
Common Format Patterns
The to_timestamp function converts a string into a timestamp by following the format string you've provided. Failing to match the input string with the correct format will lead to unexpected results.
You can construct the format strings and use the below template patterns to format date and time values.
Pattern | Description |
HH | Hour of Day (01-12) |
HH12 | Hour of Day (01-12) |
HH24 | Hour of Day (00-23) |
Y | Last Digit of Year |
YY | Last Two Digits of the Year |
YYY | Last Three Digits of the Year |
YYYY | Last Four Digits of the Year |
Y,YYY | Year in Four Digits with Comma |
MI | Minute(00-59) |
SS | Second(00-59) |
MS | Millisecond (000-999) |
US | Microsecond (000000-999999) |
SSSS | Seconds Past Midnight (0-86399) |
AM or A.M. or PM or P.M. | Meridian Indicator (Uppercase) |
am or a.m. or pm or p.m. | Meridian Indicator (Lowercase) |
BC or B.C. or AD or A.D. | Era Indicator (Uppercase) |
bc or b.c. or ad or a.d. | Era Indicator (Lowercase) |
IYYY | ISO Year (4 and more digits) |
IYY | Last Three Digits of ISO Year |
IY | Last Two Digits of ISO Year |
I | Last Digits of ISO Year |
MONTH | Full Uppercase Month Name |
Month | Full Mixed-Case Month Name |
month | Full Lowercase Month Name |
mon | Abbreviated Lowercase Month Name |
MM | Month Number (01-12) |
Examples of Using to_timestamp
Exampe 1: Converting a Simple Date String
- The query
SELECT
to_timestamp
('04-12-2002', 'DD-MM-YYYY')
;
converts the date string '
04-12-2002
'
, which is in the format '
DD-MM-YYYY
'
, into a timestamp.
- The
to_timestamp
function takes two arguments: the date string and the format mask. In this case, the format mask '
DD-MM-YYYY
'
tells PostgreSQL how to interpret the string, resulting in a valid timestamp that can be used in date and time operations.
Query:
SELECT to_timestamp('04-12-2002', 'DD-MM-YYYY');
Output:
Simple data stringExplanation:
- In this example, '04-12-2002' is the input string representing a date.
- The format string 'DD-MM-YYYY' specifies how the day, month, and year are arranged.
- PostgreSQL uses this format to convert the string into a timestamp
Exampe 2: Converting a Date and Time String
- The query
SELECT
to_timestamp('
2002-12-04 12:30:00
', '
YYYY-MM-DD HH24:MI:SS
');
converts the string '
2002-12-04 12:30:00
'
, which includes both date and time, into a timestamp.
- The format mask
'
YYYY-MM-DD HH24:MI:SS
'
specifies how the string should be parsed, resulting in a precise timestamp suitable for detailed time operations.
Query:
SELECT to_timestamp('2002-12-04 12:30:00', 'YYYY-MM-DD HH24:MI:SS');
Output:
Date and time stringExplanation:
- In this case, the input string '2002-12-04 12:30:00' includes both the date and time.
- The format string 'YYYY-MM-DD HH24:MI' ensures that PostgreSQL can correctly interpret the data as year, month, day, hour, minute, and second.
Exampe 3: Using a Compact Date Format
- The query
SELECT
to_timestamp('
20021204
', '
YYYYMMDD
')
converts the date string '
20021204
'
, which is in the compact format '
YYYYMMDD
'
into a timestamp.
- The format mask
'
YYYYMMDD
'
tells PostgreSQL how to interpret the string, resulting in a timestamp that represents December 4, 2002.
Query:
SELECT to_timestamp('20021204', 'YYYYMMDD');
Output:
Date StringExplanation:
The input string '20021204' is a compact date format. By providing the format string 'YYYYMMDD', PostgreSQL is able to correctly parse the year, month, and day. The timestamp will be generated with a default time of 00:00:00.
Conclusion
The to_timestamp
function in PostgreSQL is a versatile tool for converting date and time values stored as strings into proper timestamp data types. By specifying the correct format, you can convert a wide variety of date and time formats into timestamp values that can be used for calculations, comparisons, or storage.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read