Practical Timestamp Usage
Common Timestamp Operations
graph TD
A[Timestamp Operations] --> B[Insertion]
A --> C[Querying]
A --> D[Manipulation]
A --> E[Filtering]
Timestamp Insertion Techniques
Basic Insertion Methods
-- Automatic Current Timestamp
INSERT INTO events (event_name) VALUES ('User Login');
-- Explicit Timestamp Specification
INSERT INTO logs (log_message, created_at)
VALUES ('System Check', '2023-06-15 14:30:00');
Advanced Querying Strategies
Time-Based Filtering
-- Find records within specific time range
SELECT * FROM user_activities
WHERE created_at BETWEEN
'2023-01-01 00:00:00' AND '2023-12-31 23:59:59';
-- Find recent records
SELECT * FROM transactions
WHERE created_at >= NOW() - INTERVAL 1 WEEK;
Timestamp Manipulation Functions
Function |
Description |
Example |
DATE() |
Extract date |
SELECT DATE(created_at) |
TIME() |
Extract time |
SELECT TIME(created_at) |
YEAR() |
Extract year |
SELECT YEAR(created_at) |
TIMESTAMPDIFF() |
Calculate time difference |
TIMESTAMPDIFF(HOUR, start_time, end_time) |
Practical Ubuntu MySQL Example
## Create demonstration database
mysql -u root -p -e "
CREATE DATABASE labex_timestamp_demo;
USE labex_timestamp_demo;
CREATE TABLE user_sessions (
session_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
logout_time TIMESTAMP NULL
);
## Insert sample data
INSERT INTO user_sessions (user_id) VALUES (1);
INSERT INTO user_sessions (user_id) VALUES (2);
## Complex timestamp query
SELECT
user_id,
login_time,
TIMESTAMPDIFF(MINUTE, login_time, NOW()) as session_duration
FROM user_sessions;
"
Time Zone Handling
-- Set session time zone
SET time_zone = '+00:00';
-- Convert timestamps between time zones
SELECT CONVERT_TZ(created_at, 'UTC', 'America/New_York') as local_time
FROM events;
- Index timestamp columns used in frequent queries
- Use appropriate timestamp ranges
- Avoid unnecessary time zone conversions
- Leverage MySQL's built-in timestamp functions
Real-World Use Cases
- User activity tracking
- System logging
- Transaction timestamps
- Performance monitoring
- Audit trail maintenance
By mastering these practical timestamp techniques, developers can create more dynamic and informative database designs with LabEx's recommended approaches.