TechEarl

How to Format a MySQL DATETIME in a SELECT

Format a MySQL DATETIME in a SELECT using DATE_FORMAT, common patterns for ISO-8601 and human-readable output, CONVERT_TZ for timezone-correct dashboards, and how to store dates and time zones (DATETIME vs TIMESTAMP, UTC plus an IANA zone) so the value you format is right.

Ishan KarunaratnePublished ⏱️ 13 min readUpdated
Share thisCopied
Format a MySQL DATETIME in a SELECT with DATE_FORMAT and CONVERT_TZ, plus how to store dates and time zones: DATETIME vs TIMESTAMP, UTC, and IANA zone names.

To format a MySQL DATETIME in a SELECT, use DATE_FORMAT(value, format_string). For example, DATE_FORMAT(occurred_at, '%Y-%m-%d %H:%i:%s') returns 2025-08-14 14:32:07. The format string is built from percent-coded specifiers, like printf for dates, and the function returns a string, not a date. It has behaved the same way since MySQL 4. Further down, the page also covers the storage side: DATETIME vs TIMESTAMP and time zones, so the value you format is the right instant.

The interesting parts are the format string itself, the few presets worth memorising, and CONVERT_TZ for timezone-correct output when the column is stored in UTC. I'll walk all of those on an events table, the kind of analytics-friendly schema where you constantly need to render the same timestamp three different ways for three different dashboards.

SQL
CREATE TABLE events (
  id            BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  event_type    VARCHAR(60)     NOT NULL,
  actor_id      INT UNSIGNED    NOT NULL,
  occurred_at   DATETIME        NOT NULL,
  metadata      JSON            NULL
);
Try it with your own values

Jump to:

DATE_FORMAT basics

The shortest correct form. Pass a DATE, DATETIME, or TIMESTAMP value and a format string of percent-coded specifiers.

SQL
SELECT id, event_type,
     DATE_FORMAT(occurred_at, '%Y-%m-%d %H:%i:%s') AS occurred_iso,
     DATE_FORMAT(occurred_at, '%W, %M %D, %Y')    AS occurred_readable
FROM events
ORDER BY occurred_at DESC
LIMIT 10;

The %Y-%m-%d %H:%i:%s form produces output like 2025-08-14 14:32:07, which is the ISO-8601-ish form most APIs and log systems want. The %W, %M %D, %Y form produces Thursday, August 14th, 2025, which is the human-readable form a marketing email or admin dashboard expects.

The function returns a string, not a date. If you need to do further date arithmetic on the result, you've gone too far, keep the column raw inside the query and only DATE_FORMAT it in the final SELECT list.

Works on MySQL 5.5, 5.6, 5.7, 8.0, and 8.4.

Common format presets

The five format patterns that cover 95% of real-world use cases:

SQL
SELECT
-- ISO 8601 with seconds (logs, APIs, JSON)
DATE_FORMAT(occurred_at, '%Y-%m-%dT%H:%i:%sZ')        AS iso_8601,

-- Date only (reports, daily aggregations)
DATE_FORMAT(occurred_at, '%Y-%m-%d')                  AS date_only,

-- US-style human readable
DATE_FORMAT(occurred_at, '%M %D, %Y at %h:%i %p')     AS us_human,

-- EU-style numeric
DATE_FORMAT(occurred_at, '%d/%m/%Y %H:%i')            AS eu_numeric,

-- RFC 2822 (email Date: headers)
DATE_FORMAT(occurred_at, '%a, %d %b %Y %H:%i:%s')     AS rfc_2822
FROM events LIMIT 5;

A few specifier rules worth knowing:

  • %i is minutes, not %m (which is month). The two are commonly confused because most other formatting libraries use %M for month and %m for minutes; MySQL inverted them.
  • %h is 12-hour clock, %H is 24-hour. Add %p (AM/PM) when using %h.
  • %D is the day with English suffix (1st, 2nd, 3rd, 4th). %d is zero-padded numeric (01, 02).

The full specifier table

Reference table for the specifiers you'll actually reach for. There are a dozen more obscure ones for things like ISO week numbers; check the official docs for those.

SpecifierMeaningExample output
%Y4-digit year2025
%y2-digit year25
%mMonth, zero-padded01-12
%cMonth, no padding1-12
%MMonth name, fullJanuary
%bMonth name, abbreviatedJan
%dDay of month, zero-padded01-31
%eDay of month, no padding1-31
%DDay with English suffix1st, 2nd, 23rd
%WWeekday name, fullMonday
%aWeekday name, abbreviatedMon
%HHour, 24-hour, zero-padded00-23
%hHour, 12-hour, zero-padded01-12
%iMinutes00-59
%sSeconds00-59
%pAM or PMAM, PM
%jDay of year001-366
%UWeek of year (Sunday-first)00-53

Anything in the format string that is not a %-prefixed specifier passes through literally. So '%Y-%m-%d' produces 2025-08-14 because the dashes are literal characters between specifiers.

Timezone conversion with CONVERT_TZ

A common operational rule: store DATETIME columns in UTC, render in the user's local timezone for display. CONVERT_TZ(value, from_tz, to_tz) does the conversion inside the query.

SQL
SELECT id, event_type,
     occurred_at                                              AS utc_raw,
     CONVERT_TZ(occurred_at, 'UTC', 'America/New_York')       AS eastern,
     CONVERT_TZ(occurred_at, 'UTC', 'Europe/London')          AS london,
     CONVERT_TZ(occurred_at, 'UTC', 'Asia/Tokyo')             AS tokyo
FROM events
ORDER BY occurred_at DESC LIMIT 5;

Note CONVERT_TZ requires the MySQL timezone tables to be populated. Verify with SELECT NOW() = CONVERT_TZ(NOW(), 'UTC', 'UTC');, if it returns 1, the function works; if it returns NULL, the tables are empty.

To populate the timezone tables on Linux:

BASH
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

After loading, restart the MySQL service. On managed databases like RDS the tables are usually pre-loaded; if they are not, the cloud provider's docs explain how to enable them.

Numeric-offset conversions like CONVERT_TZ(occurred_at, '+00:00', '-05:00') work without the timezone tables, but they don't respect daylight-saving transitions. Use named zones for anything user-facing.

Relative dates: "3 days ago" output

MySQL does not have a built-in "humanize" function for relative-time output, but TIMESTAMPDIFF makes it a one-liner.

SQL
SELECT id, event_type, occurred_at,
CASE
  WHEN TIMESTAMPDIFF(MINUTE, occurred_at, NOW()) < 1   THEN 'just now'
  WHEN TIMESTAMPDIFF(MINUTE, occurred_at, NOW()) < 60  THEN CONCAT(TIMESTAMPDIFF(MINUTE, occurred_at, NOW()), ' minutes ago')
  WHEN TIMESTAMPDIFF(HOUR,   occurred_at, NOW()) < 24  THEN CONCAT(TIMESTAMPDIFF(HOUR,   occurred_at, NOW()), ' hours ago')
  WHEN TIMESTAMPDIFF(DAY,    occurred_at, NOW()) < 30  THEN CONCAT(TIMESTAMPDIFF(DAY,    occurred_at, NOW()), ' days ago')
  WHEN TIMESTAMPDIFF(MONTH,  occurred_at, NOW()) < 12  THEN CONCAT(TIMESTAMPDIFF(MONTH,  occurred_at, NOW()), ' months ago')
  ELSE CONCAT(TIMESTAMPDIFF(YEAR, occurred_at, NOW()), ' years ago')
END AS relative
FROM events
ORDER BY occurred_at DESC LIMIT 10;

For dashboard display this is fine. For anything user-facing that needs precise pluralisation ("1 minute ago" not "1 minutes ago") or i18n, do the humanise step in the application layer, MySQL's CASE syntax is not the right tool for that level of detail.

What about TIMESTAMP vs DATETIME?

TIMESTAMP and DATETIME both store a date and time, to the second by default and down to microseconds with an explicit precision such as DATETIME(6), but they differ in two ways that matter. TIMESTAMP is stored in UTC and converted to the connection's session time zone on read and write, with a narrow 1970 to 2038 range; DATETIME stores the literal value with no time-zone awareness and a 1000 to 9999 range. For business dates I store DATETIME in UTC; TIMESTAMP earns its place on audit columns. The two differences in detail:

  • TIMESTAMP is stored in UTC and converted to the connection's session timezone on read/write. If your session is +05:00, INSERT NOW() stores UTC but SELECT col returns the value in +05:00. This is convenient if every client uses the same timezone, terrible otherwise.
  • DATETIME is stored as-is with no timezone awareness. Whatever you put in is what you get out, byte-for-byte. The application layer is responsible for knowing what timezone the value is in.

Either way, store instants in UTC and convert in the query (with CONVERT_TZ) or in the application layer. TIMESTAMP has a narrow valid range (1970-2038) and the implicit conversion bites you when you connect with the wrong session timezone, so DATETIME in UTC is the safer default for business dates; TIMESTAMP still earns its place on audit columns. The full storage-side decision is in the next section.

For DATE_FORMAT purposes, both types work identically.

Store dates and time zones in MySQL

Formatting is the output end. The storage end decides whether the value you format is even the right instant. The rule that avoids almost every time-zone bug: store every instant in UTC and convert only at the edges. MySQL has no timestamp with time zone type like PostgreSQL's timestamptz, so if you also need the original local zone, keep its IANA name in a separate column. MariaDB mirrors MySQL's DATETIME/TIMESTAMP semantics exactly and has no zone-carrying type either, so all of this ports unchanged.

DATETIME is zone-naive: you write 2017-11-14 09:00:00, MySQL stores those digits, and every client reads the same digits back. TIMESTAMP is zone-aware: insert 09:00 from a session in America/New_York and MySQL stores the UTC instant 14:00; a client in Europe/London reads 14:00 back. The conversion follows the connection's time_zone setting, which is why the two types look identical until a server's zone changes or a client connects from another region.

A MySQL 8.0 session with the session time zone set to plus 09:00, where a TIMESTAMP column reads back as 21:00 after conversion while a DATETIME column stays at the stored 12:00 unchanged.
With the session zone set to plus 09:00, the TIMESTAMP column converts and reads back as 21:00, while the DATETIME column returns the stored 12:00 verbatim. Real output from MySQL 8.0.
PropertyDATETIMETIMESTAMP
Base storage5 bytes4 bytes
Fractional seconds+0 to 3 bytes+0 to 3 bytes
Range1000-01-01 to 9999-12-311970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC
Time-zone behaviorNone (stored verbatim)Session zone to UTC on write, UTC to session zone on read
ON UPDATE CURRENT_TIMESTAMPSupportedSupported
The 2038 problemNot affectedAffected (signed 32-bit UTC seconds)

Fractional seconds cost +1 byte for 1 to 2 digits, +2 for 3 to 4 and +3 for 5 to 6, so a DATETIME(6) is 8 bytes and a TIMESTAMP(6) is 7.

My default split: TIMESTAMP for audit columns (created_at, updated_at), where MySQL's automatic UTC normalization and DEFAULT/ON UPDATE CURRENT_TIMESTAMP save code and the 2038 cap does not matter for recent activity. DATETIME holding UTC (your app sets SET time_zone = '+00:00' on connect or works in UTC end to end) for business dates, far-future dates like subscription expiries, and anything that must outlive 2038. What you must never do is store a local wall-clock time without its zone: 2017-11-05 01:30:00 in America/New_York occurs twice on the autumn DST fall-back, and a bare DATETIME cannot tell which.

Keeping the original local zone. When an event listing must say "starts 7:00 PM venue time", store two things: the UTC instant and the IANA zone name ('America/New_York') in a VARCHAR. Not a fixed offset like -05:00, because a city's offset changes with DST and the IANA name is what lets a library compute the right one, even after a government changes the rules.

sql
CREATE TABLE events (
  id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  title       VARCHAR(200)    NOT NULL,
  -- the instant the event starts, stored in UTC
  starts_at   DATETIME        NOT NULL,
  -- the IANA zone the event is "in", for local-time display
  tz          VARCHAR(64)     NOT NULL DEFAULT 'UTC',
  -- audit columns: MySQL stamps these in UTC, no app code needed
  created_at  TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at  TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP
                                        ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;

-- a 7:00 PM event in New York on 2026-06-15.
-- 7:00 PM EDT is 23:00 UTC, so starts_at holds the UTC instant.
INSERT INTO events (title, starts_at, tz)
VALUES ('Summer meetup', '2026-06-15 23:00:00', 'America/New_York');

SELECT
  title,
  starts_at                              AS starts_at_utc,
  CONVERT_TZ(starts_at, '+00:00', tz)    AS starts_at_local,
  tz
FROM events;
-- starts_at_local for the row above: 2026-06-15 19:00:00 (7:00 PM)
A live MySQL session comparing DATETIME and TIMESTAMP, showing the create statement and the real query output.
A live MySQL 8 session running this schema: the real output, not illustrative.

The named-zone CONVERT_TZ needs the time-zone tables from the CONVERT_TZ section. Many teams skip database conversion and convert in the application instead, where a full IANA database ships with the runtime; the storage pattern is the same either way.

What to do next

If your reporting query also needs to group by formatted dates (daily aggregates, monthly summaries), the same DATE_FORMAT works inside GROUP BY. Wrapping the column in a function disables index use on it, though, for large tables, prefer grouping by the raw DATE(:column) and then DATE_FORMAT the result in the outer SELECT.

The events table here is also a natural place for duplicate detection if your application sometimes double-logs (webhook retries, retry storms): How to Find Duplicate Rows in MySQL covers the three patterns for catching duplicate event rows by hash, by ID, or by composite key.

For the wider reference covering date arithmetic, TIMESTAMPDIFF, STR_TO_DATE, and the rest of the date/time syntax in one place, the MySQL Cheat Sheet keeps it all on a single searchable page.

External reference: official documentation on DATE_FORMAT specifiers and CONVERT_TZ and timezone support.

FAQ

%m is month (01-12), %i is minutes (00-59). MySQL inverts the convention used by most other formatting libraries (PHP, strftime, Python), which use %M for month and %m for minutes, this is the most common DATE_FORMAT mistake.

In MySQL: %Y-%m-%d %H:%i:%s for "year-month-day hour:minute:second".

The MySQL timezone tables are empty. CONVERT_TZ needs them populated to resolve named zones like 'America/New_York'; without the tables, it cannot map the name to a UTC offset and returns NULL.

Load the tables with mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql on Linux, then restart MySQL. On managed databases, check the provider's documentation, usually the tables are pre-loaded, but on some providers you have to enable them via a parameter group.

You can, but you usually shouldn't. Wrapping a column in DATE_FORMAT in a WHERE clause prevents MySQL from using any index on that column, because the indexed values are the raw datetimes, not the formatted strings.

For "find rows on a specific date", prefer WHERE col >= '2025-08-14' AND col < '2025-08-15'. For "find rows in a specific month", prefer WHERE col >= '2025-08-01' AND col < '2025-09-01'. Both are index-friendly.

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') for ISO-8601 of the current moment. CURDATE() returns just today's date, CURTIME() returns just the time; both can also be wrapped in DATE_FORMAT.

For UTC specifically, use UTC_TIMESTAMP() instead of NOW(). NOW() returns the server's session timezone, which on a misconfigured server might not be what you expect.

Use TIMESTAMP for audit columns like created_at and updated_at: it converts to UTC automatically and supports DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, but it cannot represent dates past 2038-01-19. Use DATETIME (holding a UTC value, with your app working in UTC) for business dates, far-future dates, and anything that must outlive 2038.

No. MySQL has no timestamptz equivalent, and neither does MariaDB. TIMESTAMP normalizes values to UTC and discards the original zone, and DATETIME stores a zone-naive literal. To recover an event's original local zone, store the instant in UTC plus a VARCHAR(64) column holding the IANA zone name ('America/New_York'), not a fixed offset, because offsets change with DST.

Usually no. A BIGINT Unix timestamp is zone-free and dodges the 2038 cap, but you give up everything MySQL knows about dates: no DATE_FORMAT, awkward range queries, and an opaque number for every human reading the table. A UTC DATETIME gets you the same zone-safety and far-future range while staying a real date column. Use an integer epoch only when interoperating with a system that already speaks Unix seconds end to end.

Add a fractional-seconds precision: DATETIME(6) or TIMESTAMP(6) stores microseconds. The precision can be 0 to 6 and costs +1 byte for 1 to 2 digits, +2 for 3 to 4, and +3 for 5 to 6. Use NOW(6) or CURRENT_TIMESTAMP(6) to capture sub-second values.

No. TO_CHAR is an Oracle and PostgreSQL function; MySQL's equivalent for dates is DATE_FORMAT, and for numbers it is FORMAT.

If you are porting Oracle / PostgreSQL queries, the format specifiers are different too, YYYY-MM-DD HH24:MI:SS in Oracle becomes %Y-%m-%d %H:%i:%s in MySQL.

Sources

Authoritative references this article was fact-checked against.

TagsMySQLDATETIMETIMESTAMPDATE_FORMATCONVERT_TZTimezonesUTCData Formatting

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Export a MySQL table to CSV with SELECT INTO OUTFILE, mysqldump --tab, or the mysql client, and import a CSV back with LOAD DATA INFILE or mysqlimport.

How to Export a MySQL Table to CSV

Export a MySQL table to CSV using SELECT INTO OUTFILE, mysqldump --tab, the mysql client with a piped redirect, or a no-privilege one-liner that works on hosts where FILE is disabled. Plus the reverse: importing a CSV with LOAD DATA INFILE, LOCAL INFILE, mysqlimport, or mysqlsh.

How to store money in MySQL: why FLOAT and DOUBLE drift, DECIMAL(19,4) for exact fixed-point amounts, BIGINT integer cents for high-volume ledgers, and a separate CHAR(3) ISO 4217 currency column.

How to Store Money in MySQL: DECIMAL vs Integer Cents

Never use FLOAT or DOUBLE for money. Use DECIMAL(19,4) for exact fixed-point amounts, or BIGINT integer cents for high-volume ledgers, and always store the ISO 4217 currency code separately. Comparison, worked schema, and the rounding rules.

Back up every MySQL database with mysqldump in one command. Covers --single-transaction, --routines, --events, --hex-blob, gzip compression, restoring from the dump, cron schedules, and modern alternatives (MySQL Shell, Percona XtraBackup).

How to Export All MySQL Databases with mysqldump

Back up every MySQL (and MariaDB) database in one command with mysqldump, including --single-transaction for InnoDB consistency, gzip compression, restore steps, and the modern alternatives (MySQL Shell, Percona XtraBackup).