[Python] Converting Datetime to ISO 8601 Strings: Handling Timezones

When exchanging date and time data as strings for Web APIs or databases, the international standard ISO 8601 format (e.g., 2025-12-15T10:00:00+09:00) is widely used.

To convert a Python datetime object into this format, you use the isoformat() method. This article also explains how to explicitly handle timezones using the zoneinfo module to ensure accurate time representation.

目次

Implementation Example: Generating Timestamps for API Requests

In this scenario, we retrieve the current time in Japan Standard Time (JST) and convert it into an ISO 8601 string for integration with other systems.

Source Code

from datetime import datetime
from zoneinfo import ZoneInfo

# 1. Define Timezone (JST: Japan Standard Time)
# The zoneinfo module is available in the standard library from Python 3.9+
jst_timezone = ZoneInfo("Asia/Tokyo")

# 2. Get current time with timezone
# Specifying the tz argument creates an "Aware" object (with timezone info)
current_time_jst = datetime.now(tz=jst_timezone)

# 3. Convert to ISO 8601 string
# Generates a string with 'T' separator and timezone offset
iso_timestamp = current_time_jst.isoformat()

print(f"Datetime Object : {current_time_jst}")
print(f"ISO 8601 String : {iso_timestamp}")

# Reference: Specifying precision (e.g., seconds only, removing microseconds)
iso_timestamp_sec = current_time_jst.isoformat(timespec='seconds')
print(f"ISO 8601 (Sec)  : {iso_timestamp_sec}")

Execution Result

Datetime Object : 2025-12-15 18:30:45.123456+09:00
ISO 8601 String : 2025-12-15T18:30:45.123456+09:00
ISO 8601 (Sec)  : 2025-12-15T18:30:45+09:00

Explanation

What is ISO 8601 Format?

It is a format where the date and time are separated by a T, and the time difference (offset) from UTC is appended to the end. The +09:00 in the output above indicates that the time is 9 hours ahead of Coordinated Universal Time (UTC), representing Japan Time. This allows systems anywhere in the world to interpret the exact time correctly.

zoneinfo and Aware Objects

Calling datetime.now() without arguments creates a “Naive” object that holds no timezone information. However, when outputting in ISO format, it is recommended to include the timezone offset. Therefore, it is important to generate an “Aware” object by specifying ZoneInfo("Asia/Tokyo").

isoformat() Method

By default, the output format is YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM. You can adjust the precision using the timespec argument (e.g., 'seconds' for seconds precision, 'milliseconds' for milliseconds precision).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次