MySQL Time Zone Settings & Troubleshooting: A Complete Guide

目次

1. Introduction: Why MySQL Time Zone Settings Matter

In database administration and web application development, MySQL time zone settings are a crucial factor. Accurate date‑time data is essential for reservation systems, log management, data analysis, and more. However, if the time zone setting is wrong, the following problems can arise.

1-1. Impact of Time Zone Setting Mistakes

  1. Reservation time offsets
  • In reservation systems, time zone offsets can cause reservation times to be recorded incorrectly, potentially leading to disputes with users.
  1. Log data inconsistencies
  • If system logs or error logs are recorded in different time zones, pinpointing the cause of an issue becomes difficult.
  1. Analysis data errors
  • When analysis relies on dates and times, using offset time data can lead to incorrect conclusions.

1-2. Article Purpose and Audience

This article provides a detailed explanation of MySQL time zone settings for beginners to intermediate users. Specifically, you will learn the following.
  • How to check the current time zone setting
  • How to set it permanently and temporarily
  • How to troubleshoot issues
As a result, readers will be able to control MySQL time zone settings at will.

2. Basic Knowledge About MySQL Time Zone Settings

In MySQL, the server’s system time and the database’s time zone setting can differ. This section explains each role and how to verify the settings.

2-1. Difference Between System Time and Time Zone

  1. System Time (system_time_zone)
  • The default time setting based on the OS time zone where the MySQL server is running. It may be reset when the server restarts.
  1. Time Zone (time_zone)
  • A time zone setting managed on the database side. It is applied during interactions with applications and when executing SQL queries.

2-2. How to Check the Current Time Zone Setting

Use the following commands to check MySQL’s time zone settings.
-- Check system time
SELECT @@system_time_zone;

-- Check database time
SELECTtime_zone;
This allows you to accurately understand the current configuration.

2-3. Uses of Time Zone Settings

  • Unified management of server logs: Standardizing the time zone aligns the chronology of error logs and system logs.
  • Multi‑time‑zone support: It enables applications to manage data across different time zones for global users.

3. Importing and Preparing Time Zone Data

MySQL includes some time zone data by default, but if you need the complete set you must import it separately.

3-1. Verifying the Time Zone Tables

First, check whether the time zone data exists in the database.
SELECT * FROM mysql.time_zone_name;
If the result is empty, proceed to the next step to import the data.

3-2. Steps to Import Time Zone Data

For Linux environments:
  1. Update the time zone data:
   sudo mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
  1. Verify after import:
   SELECT * FROM mysql.time_zone_name;
For Windows environments: Because Windows may not have time zone data pre‑installed, you need to download the files from the official site and import them manually.

4. Persistent and Temporary Time Zone Configuration Methods

This section provides a detailed explanation of how to change MySQL’s time zone settings to “temporary” and “persistent”. By selecting the appropriate method based on your use case, you can manage the system more flexibly.

4-1. Temporary Time Zone Setting

Temporary time zone settings are applied on a per‑session basis. Because they are reset when the database connection ends, they are used for temporary data operations and testing purposes.

How to Set

You can change the session time zone using the following SQL command.
-- Set the session time zone to Japan Standard Time (JST)
SET time_zone = '+09:00';
Alternatively, you can use a time zone name.
SET time_zone = 'Asia/Tokyo';

Verifying the Setting

To confirm that the setting has been applied correctly, run the following command.
SELECT @@session.time_zone;

4-2. Persistent Time Zone Setting

Persistent settings apply to the entire server, so they are used in production environments and long‑term operational systems. This setting remains in effect after a MySQL server restart.

Method 1: Specifying in the Configuration File

  1. Open the MySQL configuration file (my.cnf or my.ini).
  2. Add the following line to the [mysqld] section.
[mysqld]
default-time-zone = '+09:00'
Or, to specify a time zone name:
[mysqld]
default-time-zone = 'Asia/Tokyo'
  1. Restart MySQL to apply the configuration changes.
sudo systemctl restart mysql

4-3. Points to Consider When Changing Settings

  1. Verify consistency with the application
  • If the application sets its own time zone, ensure it is consistent with the server.
  1. Ensure the time zone tables are up to date
  • If the latest time zone data hasn’t been imported, errors may occur.
  1. Be aware of time differences in logs and backups
  • Existing log and backup files are based on the original time zone, so after changing, handle data carefully.

5. Application Integration and Configuration Considerations

MySQL’s time zone settings require special attention when integrating with applications. If the application’s and database’s time zones do not match, data integrity issues may arise. This section explains specific integration methods and points to watch out for.

5-1. Basics of Application Integration

When linking an application with MySQL, you need to align the server time zone and the application time zone. Below are typical configuration examples for common programming languages.

PHP and MySQL Time Zone Settings

In PHP, you can set the time zone using the date_default_timezone_set function.
<?php
// PHP time zone setting
date_default_timezone_set('Asia/Tokyo');

// Time zone setting for MySQL connection
$db = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$db->exec("SET time_zone = '+09:00'");
?>

Python and MySQL Time Zone Settings

In Python, you connect to MySQL using pymysql or mysql-connector-python.
import pymysql
import pytz
from datetime import datetime

# Specify time zone
tz = pytz.timezone('Asia/Tokyo')

# Database connection
connection = pymysql.connect(
    host='localhost',
    user='username',
    password='password',
    database='testdb',
    cursorclass=pymysql.cursors.DictCursor
)

with connection.cursor() as cursor:
    # Set time zone per session
    cursor.execute("SET time_zone = '+09:00'")
    # Test query
    cursor.execute("SELECT NOW()")
    result = cursor.fetchone()
    print("Current Time:", result['NOW()'])

5-2. Considerations When Setting Time Zones

1. Prevent Time Zone Mismatches

  • If the server and application time zone settings differ, data integrity can be compromised.

2. Date Data Storage Formats

  • When dealing with time zones, you be aware of the differences between the DATETIME and TIMESTAMP types.
-- Insert current time
INSERT INTO events (event_time) VALUES (NOW());
In this case, the results may differ between DATETIME and TIMESTAMP. Choose the type according to your use case.

6. Troubleshooting and FAQ Section

In this section, we explain common problems related to MySQL time zone settings and their solutions. We also provide FAQ-style answers to points that readers are likely to wonder about.

6-1. Common Errors and Solutions

1. Error: “Unknown or incorrect time zone”

Symptoms:
SET time_zone = 'Asia/Tokyo';
When you run this command, you may see an error message saying “Unknown or incorrect time zone”. Cause: The time zone data has not been imported into the database or is corrupted. Solution:
  1. Check the current time zone data:
SELECT * FROM mysql.time_zone_name;
  1. If the time zone data is empty, import it using the following command:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
  1. After importing, try setting it again.

2. Error: “System time zone differs from database time zone”

Symptoms: A warning occurs when the server’s system time and the MySQL database time zone differ. Cause: Because the system time and MySQL’s global setting do not match. Solution:
SET GLOBAL time_zone = '+09:00';

6-2. FAQ Section

Q1. Can the server and application use different time zones?

A: It is possible, but caution is required. Aligning time zones is the common best practice.

Q2. Can data stored in UTC be converted to local time?

A: You can convert it using the following SQL.
SELECT CONVERT_TZ('2023-12-23 10:00:00', 'UTC', 'Asia/Tokyo') AS converted_time;

6-3. Troubleshooting Summary

  • Common errors are caused by missing time zone data imports or mismatches with system settings.
  • Use verification and correction commands to respond quickly when errors occur.
  • The FAQ section addresses practical questions, ensuring even beginners can configure settings with confidence.

7. Summary and Next Steps

In the previous articles, we have provided an in‑depth explanation of MySQL time zone settings. In this section, we’ll briefly recap the key points and suggest the next steps for readers.

7-1. Article Key Takeaways

1. Importance of MySQL Time Zone Settings

  • Time zone settings are essential for maintaining accuracy in reservation systems, log management, and data analysis.
  • Misconfigurations can cause data drift or errors, so proper management is required.

2. Basic Knowledge and How to Verify Time Zones

  • We understood the difference between system time and database time.
  • We explained how to use SQL commands to check the current configuration.

3. Importing and Preparing Time Zone Data

  • We demonstrated how to verify and import time zone data with concrete examples.

7-2. Best Practices and Operational Tips

  1. Regularly Update Time Zone Data
  • Periodically verify that you’re using the latest time zone data and update it as needed.
  1. Validate Settings in a Test Environment
  • Before making changes in production, always test them in a staging environment.

7-3. Taking the First Step Toward Practice

Based on what you’ve learned, try configuring MySQL time zones yourself. We recommend proceeding with the following steps.
  1. Set Up and Verify Your Environment
  • Run the time zone verification command in your development environment.
  1. Practice Changing Settings
  • Try both temporary and permanent settings and observe how they behave.
  1. Simulate Error Handling
  • Apply the error‑handling techniques you learned from FAQs and troubleshooting to deepen your understanding.

7-4. Closing Message

MySQL time zone configuration is an essential skill for maintaining data accuracy and reliability. We’ve covered everything from basics to advanced topics; in real‑world operations, use the commands and best practices presented here as a flexible guide. We hope this knowledge proves useful in your future database administration and application development.