Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL TO_TIMESTAMP() Function
Next article icon

PostgreSQL TO_TIMESTAMP() Function

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

PatternDescription
HHHour of Day (01-12)
HH12Hour of Day (01-12)
HH24Hour of Day (00-23)
YLast Digit of Year
YYLast Two Digits of the Year
YYYLast Three Digits of the Year
YYYYLast Four Digits of the Year
Y,YYYYear in Four Digits with Comma
MIMinute(00-59)
SSSecond(00-59)
MSMillisecond (000-999)
USMicrosecond (000000-999999)
SSSSSeconds 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)
IYYYISO Year (4 and more digits)
IYYLast Three Digits of ISO Year
IYLast Two Digits of ISO Year
ILast Digits of ISO Year
MONTHFull Uppercase Month Name
MonthFull Mixed-Case Month Name
monthFull Lowercase Month Name
monAbbreviated Lowercase Month Name
MMMonth 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-string
Simple data string

Explanation:

  • 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:

data-and-time-string
Date and time string

Explanation:

  • 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-string
Date String

Explanation:

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.


Next Article
PostgreSQL TO_TIMESTAMP() Function
author
nikunj_sonigara
Improve
Article Tags :
  • PostgreSQL
  • Databases

Similar Reads

    PostgreSQL - CURRENT_TIMESTAMP Function
    PostgreSQL provides the 'CURRENT_TIMESTAMP() function, which returns the current date and time, along with the time zone, at the precise moment the transaction begins. This function is often used for tracking the creation or modification of records in a database.Here, we’ll look into the syntax, usa
    2 min read
    PostgreSQL - Timestamp Data Type
    PostgreSQL supports two primary temporal data types to store date and time: TIMESTAMP (without timezone) and TIMESTAMPTZ (with timezone). Understanding these data types is crucial for managing date and time effectively across different regions and time zones. In this article, we will explain the TIM
    4 min read
    PostgreSQL - CURRENT_TIME Function
    The PostgreSQL CURRENT_TIME function returns the current time and the current time zone. This function is handy when you need to work with time-sensitive data in your database applications.Let us better understand the CURRENT_TIME Function in PostgreSQL from this article.SyntaxCURRENT_TIME(precision
    2 min read
    CURRENT_TIMESTAMP() Function in SQL Server
    In SQL Server, the CURRENT_TIMESTAMP function is a widely used feature for retrieving the current date and time directly from the database server. It returns the exact moment when the SQL query is executed in the YYYY-MM-DD hh:mm:ss.mmm format.In this article, We will learn about CURRENT_TIMESTAMP()
    3 min read
    PostgreSQL - NOW() Function
    The NOW() function in PostgreSQL is a powerful and essential tool for retrieving the current date and time. This is particularly useful when recording actions like adding or updating records in our database. Using PostgreSQL NOW() function, we can efficiently track when events occur, making the data
    4 min read
    How to Extract Date From a TimeStamp in PostgreSQL
    PostgreSQL is a powerful open-source relational database management system (RDBMS). PostgreSQL is well-known for its feature-rich capabilities, standardization, and adaptability. It supports a variety of data types, complex SQL queries, and ACID properties. PostgreSQL offers scalability and durabili
    4 min read
    PostgreSQL - DATE_TRUNC Function
    The PostgreSQL DATE_TRUNC() function is a powerful tool that helps us truncate a timestamp or interval to a specified level of precision. It is particularly useful when dealing with time-based data for effective data grouping and manipulation, making it ideal for reporting, analytics, and queries wh
    4 min read
    PostgreSQL Date Functions
    PostgreSQL is widely recognized for its comprehensive support for date and time manipulations, making it an excellent choice for applications requiring precise time management and complex calculations. This article explores the core PostgreSQL date functions, covering how to retrieve the current dat
    4 min read
    PostgreSQL - TIME Data Type
    In PostgreSQL, the TIME data type is essential for applications that require precise time tracking, such as scheduling systems and event logging. This data type allows for accurate time-based entries without storing date information. PostgreSQL’s TIME data type also supports fractional seconds for u
    4 min read
    PostgreSQL - EXTRACT Function
    In PostgreSQL, the EXTRACT() function is a powerful tool used to retrieve specific components of a date or time value. Whether you need to query for a particular year, month, day, or even more detailed time attributes, EXTRACT() can help you extract these fields from date and time values efficiently
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences