Skip to main content

Date Format Functions

The strftime and strptime functions can be used to convert between DATE / TIMESTAMP values and strings. This is often required when parsing CSV files, displaying output to the user or transferring information between programs. Because there are many possible date representations, these functions accept a format string that describes how the date or timestamp should be structured.

strftime Examples​

The strftime(timestamp, format) converts timestamps or dates to strings according to the specified pattern.

SQL
SELECT strftime(DATE '1992-03-02', '%d/%m/%Y');
 strftime
------------
 02/03/1992
SQL
SELECT strftime(TIMESTAMP '1992-03-02 20:32:45', '%A, %-d %B %Y - %I:%M:%S %p');
 strftime
------------------------------------
 Monday, 2 March 1992 - 08:32:45 PM

strptime Examples​

The strptime(text, format) function converts strings to timestamps according to the specified pattern.

SQL
SELECT strptime('02/03/1992', '%d/%m/%Y');
 strptime
---------------------
 1992-03-02 00:00:00
SQL
SELECT strptime('Monday, 2 March 1992 - 08:32:45 PM', '%A, %-d %B %Y - %I:%M:%S %p');
 strptime
---------------------
 1992-03-02 20:32:45

The strptime function throws an error on failure:

SQL
SELECT strptime('02/50/1992', '%d/%m/%Y') AS x;
db error: ERROR: Could not parse string "02/50/1992" according to format specifier "%d/%m/%Y"
02/50/1992
   ^
Error: Month out of range, expected a value between 1 and 12

To return NULL on failure, use the try_strptime function:

SQL
SELECT try_strptime('02/50/1992', '%d/%m/%Y') AS x;
 x
------
 NULL

CSV Parsing​

The date formats can also be specified during CSV parsing, either in the COPY statement or in the read_csv function. This can be done by either specifying a DATEFORMAT or a TIMESTAMPFORMAT (or both). DATEFORMAT will be used for converting dates, and TIMESTAMPFORMAT will be used for converting timestamps. Below are some examples for how to use this.

In a COPY statement:

SQL
COPY dates FROM 'test.csv' (DATEFORMAT '%d/%m/%Y', TIMESTAMPFORMAT '%A, %-d %B %Y - %I:%M:%S %p');SELECT * FROM dates;
1992-03-02	1992-03-02 20:32:45

In a read_csv function:

SQL
SELECT *FROM read_csv('test.csv', dateformat = '%m/%d/%Y', timestampformat = '%A, %-d %B %Y - %I:%M:%S %p');
 d          | ts
------------+---------------------
 1992-02-03 | 1992-03-02 20:32:45

Format Specifiers​

Below is a full list of all available format specifiers.

SpecifierDescriptionExample
%aAbbreviated weekday name.Sun, Mon, ...
%AFull weekday name.Sunday, Monday, ...
%bAbbreviated month name.Jan, Feb, ..., Dec
%BFull month name.January, February, ...
%cISO date and time representation1992-03-02 10:30:20
%dDay of the month as a zero-padded decimal.01, 02, ..., 31
%-dDay of the month as a decimal number.1, 2, ..., 30
%fMicrosecond as a decimal number, zero-padded on the left.000000 - 999999
%gMillisecond as a decimal number, zero-padded on the left.000 - 999
%GISO 8601 year with century representing the year that contains the greater part of the ISO week (see %V).0001, 0002, ..., 2013, 2014, ..., 9998, 9999
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, ..., 23
%-HHour (24-hour clock) as a decimal number.0, 1, ..., 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, ..., 12
%-IHour (12-hour clock) as a decimal number.1, 2, ... 12
%jDay of the year as a zero-padded decimal number.001, 002, ..., 366
%-jDay of the year as a decimal number.1, 2, ..., 366
%mMonth as a zero-padded decimal number.01, 02, ..., 12
%-mMonth as a decimal number.1, 2, ..., 12
%MMinute as a zero-padded decimal number.00, 01, ..., 59
%-MMinute as a decimal number.0, 1, ..., 59
%nNanosecond as a decimal number, zero-padded on the left.000000000 - 999999999
%pLocale's AM or PM.AM, PM
%SSecond as a zero-padded decimal number.00, 01, ..., 59
%-SSecond as a decimal number.0, 1, ..., 59
%uISO 8601 weekday as a decimal number where 1 is Monday.1, 2, ..., 7
%UWeek number of the year. Week 01 starts on the first Sunday of the year, so there can be week 00. Note that this is not compliant with the week date standard in ISO 8601.00, 01, ..., 53
%VISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Note that %V is incompatible with year directive %Y. Use the ISO year %G instead.01, ..., 53
%wWeekday as a decimal number.0, 1, ..., 6
%WWeek number of the year. Week 01 starts on the first Monday of the year, so there can be week 00. Note that this is not compliant with the week date standard in ISO 8601.00, 01, ..., 53
%xISO date representation1992-03-02
%XISO time representation10:30:20
%yYear without century as a zero-padded decimal number. Numbers 00 to 68 are turned into 2000 to 2068. Numbers 69 to 99 are turned into 1969 to 1999.00, 01, ..., 99
%-yYear without century as a decimal number. Numbers 0 to 68 are turned into 2000 to 2068. Numbers 69 to 99 are turned into 1969 to 1999.0, 1, ..., 99
%YYear with century as a decimal number.2013, 2019 etc.
%zTime offset from UTC in the form ±HH:MM, ±HHMM, or ±HH.-0700
%ZTime zone name.Europe/Amsterdam
%%A literal % character.%

PostgreSQL Formatting Functions​

to_char, to_date and to_timestamp take a PostgreSQL template instead of a % format specifier, and follow PostgreSQL's rules for padding, fill mode and parsing. The template patterns below describe what each part of the template does; anything in the template that is not a pattern is copied to the output as is. To format numbers, use to_char(x, format) and to_number(text, format).

NameDescription
to_char(timestamp, format)Formats a timestamp, or a date, as text according to the template format.
to_char(timestamptz, format)Formats a timestamp with time zone in the session time zone.
to_char(interval, format)Formats an interval as text according to the template format.
to_date(text, format)Parses text into a date according to the template format.
to_timestamp(text, format)Parses text into a timestamp with time zone according to the template format.

to_char(timestamp, format)​

Formats a timestamp as text according to the template format. A date is formatted as a timestamp at midnight. An empty template returns NULL.

SQL
SELECT to_char(TIMESTAMP '2024-03-05 14:07:09', 'FMDay, FMDD FMMonth YYYY, HH12:MI AM') AS result;
 result
---------------------------------
 Tuesday, 5 March 2024, 02:07 PM

to_char(timestamptz, format)​

Formats a timestamp with time zone in the session time zone. TZ and tz print UTC or GMT when the session time zone is one of those, and the offset of the zone otherwise (for example +0530), where PostgreSQL prints the abbreviation of the zone, such as CET or EST. OF, TZH and TZM print the offset as PostgreSQL does.

SQL
SELECT to_char(TIMESTAMPTZ '2024-03-05 14:07:09+00', 'YYYY-MM-DD HH24:MI:SS TZ OF') AS result;
 result
-----------------------------
 2024-03-05 14:07:09 UTC +00

to_char(interval, format)​

Formats an interval. HH24 counts all the hours of the interval, and YYYY, MM and DD print its years, months and days. Patterns that need a calendar date, such as Day, Month, D or TZ, are rejected. A TIME value is formatted as the interval since midnight, as PostgreSQL does.

SQL
SELECT to_char(INTERVAL '1 day 02:03:04', 'DD "days" HH24:MI:SS') AS result;
 result
------------------
 01 days 02:03:04

to_date(text, format)​

Parses text into a date. Spaces in the template match any amount of white space, and separators match any separator, unless the template uses FX. Fields that are out of range raise an error.

SQL
SELECT to_date('05 Mar 2024', 'DD Mon YYYY') AS result;
 result
------------
 2024-03-05
SQL
SELECT to_date('2024-13-05', 'YYYY-MM-DD');
db error: ERROR: date/time field value out of range: "2024-13-05"

to_timestamp(text, format)​

Parses text into a timestamp with time zone. The text is read in the session time zone unless the template has a TZ, TZH, TZM or OF field. TZ recognizes the abbreviations UTC, GMT, UT, UCT, Z and ZULU and reads a numeric offset like OF; other abbreviations raise an error. To convert seconds since the epoch, use to_timestamp(double).

SQL
SELECT to_timestamp('2024-03-05 02:07:09 PM +02', 'YYYY-MM-DD HH12:MI:SS AM TZH') AS result;
 result
------------------------
 2024-03-05 12:07:09+00

Template Patterns​

Most patterns are also recognized in lowercase, such as yyyy, dd or q, so letters meant as text belong in double quotes.

PatternDescription
HH, HH12Hour of day (01-12).
HH24Hour of day (00-23).
MIMinute (00-59).
SSSecond (00-59).
MSMillisecond (000-999).
USMicrosecond (000000-999999).
FF1 ... FF6Tenth of a second up to microsecond, with 1 to 6 digits.
SSSS, SSSSSSeconds past midnight (0-86399).
AM, am, PM, pmMeridiem indicator without periods.
A.M., a.m., P.M., p.m.Meridiem indicator with periods.
Y,YYYYear (4 or more digits) with a comma.
YYYYYear (4 or more digits).
YYY, YY, YLast 3, 2 or 1 digits of the year.
IYYY, IYY, IY, IISO 8601 week-numbering year, or its last 3, 2 or 1 digits.
BC, bc, AD, adEra indicator without periods.
B.C., b.c., A.D., a.d.Era indicator with periods.
MONTH, Month, monthFull month name in upper, capitalized or lower case, padded to 9 characters.
MON, Mon, monAbbreviated month name in upper, capitalized or lower case.
MMMonth number (01-12).
DAY, Day, dayFull day name in upper, capitalized or lower case, padded to 9 characters.
DY, Dy, dyAbbreviated day name in upper, capitalized or lower case.
DDDDay of the year (001-366).
IDDDDay of the ISO 8601 week-numbering year (001-371).
DDDay of the month (01-31).
DDay of the week, Sunday (1) to Saturday (7).
IDISO 8601 day of the week, Monday (1) to Sunday (7).
WWeek of the month (1-5); the first week starts on the first day of the month.
WWWeek of the year (1-53); the first week starts on the first day of the year.
IWWeek of the ISO 8601 week-numbering year (01-53).
CCCentury; the 21st century starts on 2001-01-01.
JJulian Day, the number of days since November 24, 4714 BC at local midnight.
QQuarter; ignored by to_date and to_timestamp.
RM, rmMonth in upper or lower case Roman numerals, padded to 4 characters.
TZ, tzTime zone abbreviation in upper or lower case.
TZHTime zone hours.
TZMTime zone minutes.
OFTime zone offset from UTC, as +HH or +HH:MM.

Template Pattern Modifiers​

ModifierDescriptionExample
FM prefixFill mode: no padding blanks and no leading zeros.FMMonth
TH suffixUpper case ordinal number suffix.DDTH
th suffixLower case ordinal number suffix.DDth
FX prefixFixed format: to_date and to_timestamp match the template character by character.FX Month DD
TM prefixTranslation mode: day and month names in the server locale (English), without padding.TMMonth

Text in double quotes is copied as is, and a backslash before a double quote prints the double quote.