Python datetime Guide: Dates, Times, Time Zones & Examples

目次

1. Introduction

The datetime module is essential when handling dates and times in Python. By using this module, you can retrieve the current time, convert date‑time formats, perform time calculations, and many other operations. However, for Python beginners, dealing with datetime can feel a bit challenging. For example:
  • “I want to get the current date and time, but which function should I use?”
  • “I don’t know how to handle time zones!”
  • “How do I perform date calculations?”
This article clearly explains the basics to advanced usage of Python’s datetime module. Even beginners will be able to understand smoothly, as we include code examples, so please use it as a reference.

2. datetime Module? Understand the Basic Concepts

2.1 Overview of the datetime module

Python includes the datetime module as part of its standard library, allowing easy manipulation of dates and times. The datetime module contains the following major classes.
Class NameDescription
datetimeClass for handling dates and times
dateClass for handling dates only
timeClass for handling times only
timedeltaClass representing a duration
tzinfoClass for handling time zone information
Among these, the datetime class is the most commonly used.

2.2 How to import the datetime module

To use Python’s datetime module, you first need to import it. Using import datetime as shown below imports the entire module.
import datetime

# Get the current date and time
now = datetime.datetime.now()
print(now)
You can also import only specific classes.
from datetime import datetime

# Get the current date and time
now = datetime.now()
print(now)
Importing in the form from datetime import datetime allows you to avoid writing datetime twice in code, such as datetime.datetime.now(), making it simpler.
年収訴求

3. How to get the current time and today’s date in Python (difference between now and today)

3.1 How to get the current date and time

In Python, to obtain the current date and time, use datetime.now().
from datetime import datetime

now = datetime.now()
print("Current date and time:", now)
When you run this code, you get output like the following.
Current date and time: 2025-02-01 12:34:56.789012
This format is YYYY-MM-DD HH:MM:SS.ssssss, which includes the date, time, and microseconds.

3.2 How to get today’s date

If you only want today’s date, use date.today().
from datetime import date

today = date.today()
print("Today's date:", today)
Example output:
Today's date: 2025-02-01

3.3 Difference between now() and today()

MethodFunction
datetime.now()Gets the current date and time
date.today()Gets the current date only
Choose the appropriate one based on your use case.

4. Date and Time Format Conversion (String ⇔ datetime)

When working with dates and times, format conversion is extremely important. In Python, you can use strftime() and strptime() to convert between datetime objects and strings.

4.1 Converting a datetime object to a string (strftime)

If you want to convert a datetime to a string in a specific format, use strftime().
from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
Output:
Formatted date: 2025-02-01 12:34:56

4.2 Converting a string to a datetime object (strptime)

To convert a string to a datetime, use strptime().
from datetime import datetime

date_str = "2025-02-01 12:34:56"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Converted datetime object:", dt)
Output:
Converted datetime object: 2025-02-01 12:34:56

5. How to add and subtract dates in Python (using timedelta)

In Python, you can easily perform addition and subtraction of dates and times by using the timedelta class.

5.1 Basics of the timedelta class

from datetime import datetime, timedelta

# Get the current date and time
now = datetime.now()

# Get the date 7 days from now
future_date = now + timedelta(days=7)
print("Date 7 days from now:", future_date)

# Get the date 3 days ago
past_date = now - timedelta(days=3)
print("Date 3 days ago:", past_date)

5.2 Adding and subtracting in time units

from datetime import datetime, timedelta

now = datetime.now()

# Time one hour later
one_hour_later = now + timedelta(hours=1)
print("Time one hour later:", one_hour_later)

# Time 30 minutes ago
thirty_minutes_ago = now - timedelta(minutes=30)
print("Time 30 minutes ago:", thirty_minutes_ago)

5.3 Calculating the difference between two dates

from datetime import datetime

# Define two dates
date1 = datetime(2025, 2, 10)
date2 = datetime(2025, 2, 1)

# Calculate the difference
difference = date1 - date2
print("Date difference:", difference)
print("Days difference:", difference.days, "days")

6. Handling Dates and Times with Time Zone Awareness (Differences between pytz and zoneinfo)

When handling dates and times in Python, taking time zones into account is extremely important.

6.1 pytz Setting Time Zones

from datetime import datetime
import pytz

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

# Get the current UTC time
utc_now = datetime.utcnow()

# Convert to JST (Japan Standard Time)
jst_now = utc_now.replace(tzinfo=pytz.utc).astimezone(japan_tz)
print("Japan Time (JST):", jst_now)

6.2 zoneinfo (Python 3.9 and later) Setting Time Zones

from datetime import datetime
from zoneinfo import ZoneInfo

# Get the current time in JST (Japan Standard Time)
jst_now = datetime.now(ZoneInfo("Asia/Tokyo"))
print("Current JST time:", jst_now)
If you are using Python 3.9 or later, it is recommended to use zoneinfo.

7. Errors and Their Solutions

When using Python’s datetime module, there are several errors that beginners often encounter.

7.1 AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

from datetime import datetime

# Trying to use timedelta but error
now = datetime.now()
new_date = now + datetime.timedelta(days=7)
Solution:
from datetime import datetime, timedelta

now = datetime.now()
new_date = now + timedelta(days=7)
print(new_date)

7.2 TypeError: can't subtract offset-naive and offset-aware datetimes

from datetime import datetime
import pytz

dt_naive = datetime(2025, 2, 1, 12, 0)
dt_aware = datetime(2025, 2, 1, 12, 0, tzinfo=pytz.utc)

diff = dt_aware - dt_naive  # error occurs
Solution:
dt_aware = dt_naive.replace(tzinfo=pytz.utc)

8. Practical Examples

8.1 How to Generate a Date Range

from datetime import datetime, timedelta

start_date = datetime(2025, 2, 1)
end_date = datetime(2025, 2, 7)

date_list = [start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)]

for date in date_list:
    print(date.strftime("%Y-%m-%d"))

8.2 Date Calculations Considering Business Days (Weekdays)

import pandas as pd

business_days = pd.bdate_range(start="2025-02-01", end="2025-02-10")

for day in business_days:
    print(day.date())

8.3 Converting UNIX Timestamps

from datetime import datetime

timestamp = 1735689600
dt = datetime.fromtimestamp(timestamp)
print("Converted datetime:", dt)

9. FAQ (Frequently Asked Questions)

9.1 Difference between datetime and time?

Itemdatetimetime
PurposeDate and time handlingMeasuring UNIX time and sleep operations
Exampledatetime(2025, 2, 1, 12, 0, 0)time.sleep(2)

9.2 Difference between strftime and strptime?

from datetime import datetime

# datetime → string (strftime)
now = datetime(2025, 2, 1, 12, 0, 0)
formatted_str = now.strftime("%Y-%m-%d %H:%M:%S")
print("Convert to string:", formatted_str)

# string → datetime (strptime)
date_str = "2025-02-01 12:00:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Convert to datetime:", parsed_date)

9.3 How to convert a UNIX timestamp to datetime?

from datetime import datetime

timestamp = 1735689600
dt = datetime.fromtimestamp(timestamp)
print("Converted datetime:", dt)

10. Summary

10.1 Summary of Article Points

  • datetime module is the standard library for handling dates and times in Python.
  • Use datetime.now() to get the current date and time, and date.today() to get only the current date.
  • Use strftime() to convert a <code to a string, and strptime() to convert a string to a datetime.
  • Calculate the date one week later with timedelta(days=7).
  • Use zoneinfo for Python 3.9 and later, and pytz for earlier versions.
  • datetime objects can be compared using > < ==.

10.2 Official Documentation and References

10.3 Put Time Handling in Python into Practice

Develop a schedule management appAnalyze log dataPerform time calculations across different time zonesImplement an automatic reminder feature Thank you for reading to the end!
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール