Fix PostgreSQL Error 22007: Invalid Datetime Format Quickly
In this article
PostgreSQL error code 22007 ("invalid datetime format") occurs when your SQL query receives a date or timestamp that doesn't conform to PostgreSQL's expected format standards. This prevents the database from processing or storing the value properly. Fixing it requires converting your datetime string to match PostgreSQL's strict format requirements (YYYY-MM-DD, YYYY-MM-DD HH:MI:SS, or similar ISO 8601 variants) or using the correct date functions to parse invalid formats.
What You'll Need
- A working PostgreSQL client (psql, pgAdmin, or IDE with PostgreSQL support)
- The date string causing the error (check the exact format it was stored or passed)
- Basic knowledge of PostgreSQL date functions (TO_DATE, TO_TIMESTAMP, EXTRACT)
- Administrator permissions if modifying database schema
Step-by-Step Solution
- Identify the exact input causing the error
- Execute `SELECT * FROM your_table WHERE some_column IS NULL;` to find rows with potentially invalid datetime values
- For queries, check how input is being passed (connection string parameters, application code, or manual input)
- Use `psql` with `\d` to examine your table structure:
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'your_table';
- Verify PostgreSQL's current date format settings
- Run `SHOW DATESTYLE;` to see if it matches your format expectations (ISO, American, etc.)
- Check `SHOW TIMEZONE;` if timezone issues are suspected
- If needed, reset with:
ALTER SYSTEM SET TIMEZONE TO 'UTC';Then reload with `\set ON_ERROR_STOP 1` followed by `\reload` in psql
- Convert invalid formats using PostgreSQL functions
- Common conversion functions:
TO_DATE('invalid_string', 'format_pattern')- Convert string to dateTO_TIMESTAMP('invalid_string', 'format_pattern')- Convert string to timestampEXTRACT(YEAR FROM your_datetime)- Extract components from valid datetimes
- Example fixes:
- For US-style dates (MM/DD/YYYY):
SELECT TO_DATE('05/15/2023', 'MM/DD/YYYY') FROM dual; - For timezones:
SELECT TO_TIMESTAMP('2023-05-15 14:30:00', 'YYYY-MM-DD HH24:MI:SS') AT TIME ZONE 'America/New_York';
- For US-style dates (MM/DD/YYYY):
- Common conversion functions:
- Update database schema if needed
- If the column was created with incorrect data type, alter it:
ALTER TABLE your_table ALTER COLUMN your_column SET DATA TYPE timestamp WITHOUT TIME ZONE; - For existing invalid data, use:
UPDATE your_table SET your_column = TO_DATE('correct_value', 'format') WHERE your_column IS NULL; - Consider adding a default value:
ALTER TABLE your_table ALTER COLUMN your_column SET DEFAULT CURRENT_DATE;
- If the column was created with incorrect data type, alter it:
- Modify application code if using raw strings
- For application developers, ensure datetime strings match PostgreSQL format:
date_str = date_str.replace('-', '/') # Convert to US format if needed - Use parameterized queries to prevent injection:
EXECUTE 'INSERT INTO table VALUES ($1)' USING your_valid_date;
- For application developers, ensure datetime strings match PostgreSQL format:
Common Mistakes to Avoid
- Ignoring timezone differences: Data formatted as UTC but stored as local time can cause 22007 errors. Always specify timezone explicitly when converting
- Using default format patterns: PostgreSQL doesn't use US-style dates (MM/DD/YYYY) by default. Always specify your format pattern
- Assuming NULL values are clean: NULL in datetime columns can sometimes cause parsing issues. Explicitly check for NULLs in your queries
- Mismatched input/output types: Passing a string where a timestamp is expected, or vice versa, triggers this error
- Overwriting valid data with conversion: When updating, be careful not to break existing valid datetime values
- Implement data validation in your application before database insertion
- Use the `pg_checksums` extension to verify database consistency
- Create triggers to enforce proper datetime formats when inserting data
- For development, use:
SET datestyle = 'DMY';to match your locale's expected format temporarily - Document all datetime formats used in your project's schema
- Check for hidden characters or encoding issues
- Use `pg_dump` to export your table with encoding check:
pg_dump --encoding=UTF8 --file=backup.sql your_database - Examine raw data with:
SELECT hex(your_column) FROM your_table WHERE your_column IS NOT NULL;
- Use `pg_dump` to export your table with encoding check:
- Test with minimal example
- Create a new table with just one column:
CREATE TABLE test_table (invalid_date text); - Insert a known invalid format and run single queries:
INSERT INTO test_table VALUES ('2023/15/05');SELECT TO_DATE('2023/15/05', 'YYYY/MM/DD') FROM test_table;
- Create a new table with just one column:
- Check for database corruption
- Run:
VACUUM (VERBOSE, ANALYZE) your_table;to check for inconsistencies - Consider a full restore if corruption is suspected:
pg_dump -F p -f backup.dump your_database;
- Run:
- Recreate the table
- As a last resort, drop and recreate:
DROP TABLE your_table; CREATE TABLE your_table (column_name DATE); - Import data from backup or re-enter cleaned values
- As a last resort, drop and recreate:
- Contact database administrator
- If you're not the admin and the issue persists after all checks, contact DBA who may have:
- Server-specific timezone settings
- Custom date functions
- Application integration details
- If you're not the admin and the issue persists after all checks, contact DBA who may have:
Tips for Prevention
Troubleshooting When It Fails
If these steps don't resolve the issue, try these advanced approaches:
Frequently Asked Questions
Why does my PostgreSQL always show error 22007 when I use US-style dates?
PostgreSQL uses ISO 8601 format (YYYY-MM-DD) by default. US dates (MM/DD/YYYY) can cause 22007 unless you explicitly specify the format pattern like 'MM/DD/YYYY'. The error occurs because PostgreSQL doesn't understand the month/day ordering of US dates unless told to.
What should I do if my application keeps sending invalid timestamps?
Implement frontend validation that converts all datetime strings to PostgreSQL-compatible format before sending. Use JavaScript's Intl.DateTimeFormat or moment.js to standardize formats before database insertion. This prevents the error at the source.
How do I check which PostgreSQL version I'm using and how that affects datetime handling?
Run SELECT version(); in psql. Older versions (pre-9.3) had stricter date handling requirements. Version 9.3+ includes better timezone support and more flexible date functions. Check pg_config --versions if you need technical details about your installation.
What's the difference between invalid datetime format error and data type mismatch errors?
Error 22007 is specifically about the format of a timestamp string. Data type mismatch would occur if you tried to store a string in a DATE column, or a TIMESTAMP in a TEXT column. Both prevent proper database processing but come from different root causes.
Can I use wildcards or partial matching to fix datetime formats?
No, PostgreSQL requires exact format matching for date functions. While you might find records with similar but slightly different formats, you cannot use wildcards or partial patterns to successfully parse datetime strings. Always specify the complete format pattern.
What's the most efficient way to convert thousands of invalid datetime records?
The most efficient approach is to create a temporary table with the conversion logic, then use COPY to bulk load the corrected data. Example:
CREATE TEMP TABLE clean_dates AS SELECT TO_DATE('invalid', 'format') FROM your_table;
INSERT INTO your_table (column) SELECT column FROM clean_dates;
This typically handles thousands of records in seconds rather than minutes.