目次
- 1 1. Introduction
- 2 2. datetime Module? Understand the Basic Concepts
- 3 3. How to get the current time and today’s date in Python (difference between now and today)
- 4 4. Date and Time Format Conversion (String ⇔ datetime)
- 5 5. How to add and subtract dates in Python (using timedelta)
- 6 6. Handling Dates and Times with Time Zone Awareness (Differences between pytz and zoneinfo)
- 7 7. Errors and Their Solutions
- 8 8. Practical Examples
- 9 9. FAQ (Frequently Asked Questions)
- 10 10. Summary
1. Introduction
Thedatetime 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?”
datetime module. Even beginners will be able to understand smoothly, as we include code examples, so please use it as a reference.Ad
2. datetime Module? Understand the Basic Concepts
2.1 Overview of the datetime module
Python includes thedatetime module as part of its standard library, allowing easy manipulation of dates and times. The datetime module contains the following major classes.| Class Name | Description |
|---|---|
datetime | Class for handling dates and times |
date | Class for handling dates only |
time | Class for handling times only |
timedelta | Class representing a duration |
tzinfo | Class for handling time zone information |
datetime class is the most commonly used.2.2 How to import the datetime module
To use Python’sdatetime 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, usedatetime.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.789012This 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, usedate.today().from datetime import date
today = date.today()
print("Today's date:", today)Example output:Today's date: 2025-02-013.3 Difference between now() and today()
| Method | Function |
|---|---|
datetime.now() | Gets the current date and time |
date.today() | Gets the current date only |
Ad
4. Date and Time Format Conversion (String ⇔ datetime)
When working with dates and times, format conversion is extremely important. In Python, you can usestrftime() 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:564.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:565. 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 thetimedelta 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")
Ad
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.Ad
7. Errors and Their Solutions
When using Python’sdatetime 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 occursSolution:dt_aware = dt_naive.replace(tzinfo=pytz.utc)Ad
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)Ad
9. FAQ (Frequently Asked Questions)
9.1 Difference between datetime and time?
| Item | datetime | time |
|---|---|---|
| Purpose | Date and time handling | Measuring UNIX time and sleep operations |
| Example | datetime(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)Ad
10. Summary
10.1 Summary of Article Points
datetimemodule is the standard library for handling dates and times in Python.- Use
datetime.now()to get the current date and time, anddate.today()to get only the current date. - Use
strftime()to convert a <code to a string, andstrptime()to convert a string to adatetime. - Calculate the date one week later with
timedelta(days=7). - Use
zoneinfofor Python 3.9 and later, andpytzfor earlier versions. datetimeobjects can be compared using><==.



