6. Datas, Horários & Auditoria
DATETIME vs TIMESTAMP (Data + Hora)
Registros de data e hora completa (AAAA-MM-DD HH:MM:SS) para eventos, agendamentos e auditoria.
💾 Espaço em Disco: TIMESTAMP: 4 Bytes (MySQL) | DATETIME: 5 a 8 Bytes
📏 Limites: DATETIME: 1000-01-01 00:00:00 a 9999-12-31 23:59:59 | TIMESTAMP MySQL: 1970 a 2038
Ambos guardam data e hora (`YYYY-MM-DD HH:MM:SS`), mas têm uma diferença vital: o `TIMESTAMP` converte automaticamente o horário da sessão para UTC ao salvar no disco e converte de volta para o fuso horário atual ao consultar (ótimo para `created_at` e `updated_at`), ocupando 4 bytes (nota: no MySQL de 32-bits/antigo o TIMESTAMP vai até 2038; no PostgreSQL `TIMESTAMPTZ` ocupa 8 bytes e não tem limite de 2038). Já o `DATETIME` ocupa 5 a 8 bytes, vai do ano 1000 ao 9999 e guarda a data/hora literal sem conversão de fuso (ideal para agendamentos futuros como consultas médicas).
✅ Quando Usar
- •Use `TIMESTAMP` (ou `TIMESTAMPTZ` no Postgres) para carimbos de auditoria do momento exato em que algo aconteceu: `criado_em`, `atualizado_em`, `pago_em`, `deletado_em`.
- •Use `DATETIME` para datas futuras distantes (após 2038 no MySQL) ou agendamentos civis fixos (`data_hora_consulta DATETIME`).
🚫 Quando NÃO Usar
- •Não use `INT` para guardar Unix Timestamp manual se quiser usar funções de data nativas do SQL de forma legível nos relatórios e no DrawDB.
📐 Configuração no DrawDB
- Type:
- TIMESTAMP ou DATETIME
- Size / Values:
- Vazio
- Default:
- CURRENT_TIMESTAMP
MySQL / MariaDB
DATETIME ou TIMESTAMP DEFAULT CURRENT_TIMESTAMP
PostgreSQL
TIMESTAMPTZ (TIMESTAMP WITH TIME ZONE) DEFAULT CURRENT_TIMESTAMP
SQLite
DATETIME DEFAULT CURRENT_TIMESTAMP
🗄️ SQL DDL (Pronto para Importar no DrawDB)
CREATE TABLE consultas_medicas (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
paciente_id BIGINT UNSIGNED NOT NULL,
agendado_para DATETIME NOT NULL,
criado_em TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
atualizado_em TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
cancelado_em TIMESTAMP NULL DEFAULT NULL
);
🐘 Exemplo Prático em PHP 8 + PDO
<?php
declare(strict_types=1);
date_default_timezone_set('America/Sao_Paulo');
$agendamento = new DateTimeImmutable('2026-11-10 14:30:00');
$stmt = $pdo->prepare('
INSERT INTO consultas_medicas (paciente_id, agendado_para)
VALUES (:paciente_id, :agendado_para)
');
$stmt->bindValue(':paciente_id', 77, PDO::PARAM_INT);
$stmt->bindValue(':agendado_para', $agendamento->format('Y-m-d H:i:s'), PDO::PARAM_STR);
$stmt->execute();