杰瑞科技汇

Python time与datetime模块如何选择使用?

Of course! Let's break down Python's time and datetime modules. They are both fundamental for working with dates and times, but they serve different purposes and have different strengths.

Python time与datetime模块如何选择使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering both.


The Short Answer: Which One Should I Use?

  • Use datetime when you need to work with dates and times together. This is the most common scenario. It's object-oriented, more intuitive, and has a rich set of features for date arithmetic, formatting, and parsing.
  • Use time when you are primarily interested in time as a point on a clock or for measuring elapsed time. It's simpler and its functions are often used for things like performance timing (time.perf_counter()) or getting a simple timestamp (time.time()).

The datetime Module: The Powerhouse for Dates and Times

The datetime module is the go-to for most date and time operations. It provides several classes, but the most important ones are datetime, date, and time.

Key Classes in datetime

  • datetime.datetime: A combination of date and time (e.g., 2025-10-27 10:30:00).
  • datetime.date: Just a date (e.g., 2025-10-27).
  • datetime.time: Just a time (e.g., 10:30:00).
  • datetime.timedelta: Represents a duration, the difference between two dates or times. Perfect for date arithmetic.

Creating datetime Objects

import datetime
# 1. Get the current date and time
now = datetime.datetime.now()
print(f"Current datetime: {now}")
print(f"Current date: {now.date()}")
print(f"Current time: {now.time()}")
# Output (example):
# Current datetime: 2025-10-27 10:30:00.123456
# Current date: 2025-10-27
# Current time: 10:30:00.123456
# 2. Create a specific datetime from integers
# Year, Month, Day, Hour, Minute, Second, Microsecond
specific_dt = datetime.datetime(2025, 10, 27, 15, 45, 30)
print(f"\nSpecific datetime: {specific_dt}")
# Output: Specific datetime: 2025-10-27 15:45:30
# 3. Create a specific date (returns a date object)
specific_date = datetime.date(2025, 10, 27)
print(f"Specific date: {specific_date}")
# Output: Specific date: 2025-10-27
# 4. Create a specific time (returns a time object)
specific_time = datetime.time(10, 30, 0)
print(f"Specific time: {specific_time}")
# Output: Specific time: 10:30:00

Formatting and Parsing (Converting to/from Strings)

This is a very common task. The strftime() method formats a datetime object into a string, and strptime() parses a string into a datetime object.

  • strftime() -> str from time
  • strptime() -> str parsed time

Common Format Codes:

Python time与datetime模块如何选择使用?-图2
(图片来源网络,侵删)
  • %Y: 4-digit year (e.g., 2025)
  • %m: 2-digit month (e.g., 10 for October)
  • %d: 2-digit day of the month (e.g., 27)
  • %H: 2-digit hour (24-hour clock)
  • %M: 2-digit minute
  • %S: 2-digit second
  • %A: Full weekday name
  • %B: Full month name
import datetime
dt = datetime.datetime(2025, 10, 27, 15, 45, 30)
# --- Formatting (datetime -> string) ---
formatted_str = dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted as YYYY-MM-DD: {formatted_str}")
formatted_str_2 = dt.strftime("%B %d, %Y at %I:%M %p")
print(f"Formatted nicely: {formatted_str_2}")
# Output:
# Formatted as YYYY-MM-DD: 2025-10-27 15:45:30
# Formatted nicely: October 27, 2025 at 03:45 PM
# --- Parsing (string -> datetime) ---
date_string = "2025-12-25 09:00:00"
dt_from_string = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed datetime object: {dt_from_string}")
print(f"Type of parsed object: {type(dt_from_string)}")
# Output:
# Parsed datetime object: 2025-12-25 09:00:00
# Type of parsed object: <class 'datetime.datetime'>

Date and Time Arithmetic

This is where datetime truly shines. You can perform calculations using timedelta objects.

import datetime
today = datetime.date.today()
# Calculate a future date
five_days_later = today + datetime.timedelta(days=5)
print(f"Today: {today}")
print(f"5 days later: {five_days_later}")
# Calculate a past date
two_weeks_ago = today - datetime.timedelta(weeks=2)
print(f"2 weeks ago: {two_weeks_ago}")
# Calculate the difference between two dates
diff = today - two_weeks_ago
print(f"The difference is: {diff} days")
print(f"The difference is: {diff.days} days") # Access just the days
# You can also add/subtract hours, minutes, seconds
now = datetime.datetime.now()
one_hour_and_half_ago = now - datetime.timedelta(hours=1, minutes=30)
print(f"\nNow: {now}")
print(f"1.5 hours ago: {one_hour_and_half_ago}")

The time Module: Simpler, Low-Level Time Access

The time module provides access to functions for working with time, primarily related to the C library. It's less about "calendar dates" and more about "time since an epoch" or "wall-clock time".

Key Functions in time

  • time.time(): Returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC). This is a floating-point number. Great for unique IDs or measuring elapsed time.
  • time.ctime(): Returns a human-readable string representing the current local time. E.g., Fri Oct 27 10:30:00 2025.
  • time.sleep(seconds): Suspends the execution of the current thread for the given number of seconds. Very useful for delays in scripts.
import time
# 1. Get the current time in seconds since the epoch
timestamp = time.time()
print(f"Timestamp (seconds since epoch): {timestamp}")
# Output: Timestamp (seconds since epoch: 1698370200.123456
# 2. Convert a timestamp to a readable string
readable_time = time.ctime(timestamp)
print(f"Readable time from timestamp: {readable_time}")
# Output: Readable time from timestamp: Fri Oct 27 10:30:00 2025
# 3. Get the current time as a readable string directly
current_time_str = time.ctime()
print(f"Current readable time: {current_time_str}")
# Output: Current readable time: Fri Oct 27 10:30:00 2025
# 4. time.sleep() - Example
print("Starting...")
time.sleep(2) # Pause for 2 seconds
print("...2 seconds later.")

time.struct_time

Many functions in the time module (like time.localtime(), time.gmtime()) return or accept a struct_time object. It's like a named tuple for holding time components.

import time
# Get the current time as a struct_time
local_time_struct = time.localtime()
print(f"Local time as struct_time: {local_time_struct}")
print("\nAccessing components:")
print(f"Year: {local_time_struct.tm_year}")
print(f"Month: {local_time_struct.tm_mon}")
print(f"Day of month: {local_time_struct.tm_mday}")
print(f"Hour: {local_time_struct.tm_hour}")
print(f"Day of the week (0=Monday): {local_time_struct.tm_wday}")
# You can also format a struct_time into a string
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time_struct)
print(f"\nFormatted from struct_time: {formatted_time}")

Comparison Table: datetime vs. time

Feature / Aspect datetime Module time Module
Primary Purpose Working with calendar dates and times together. Low-level time access, performance timing, timestamps.
Main Data Type datetime, date, time objects. Floats (seconds since epoch), struct_time.
Getting Current Time datetime.datetime.now() time.time(), time.ctime()
Date Arithmetic Excellent. Uses timedelta for adding/subtracting days, hours, etc. None. Not designed for this.
Formatting/Parsing Excellent. strftime() and strptime() are powerful and standard. Good. time.strftime() and time.strptime() work with struct_time.
Time Zones Yes (with pytz or Python 3.9+ zoneinfo). Essential for robust applications. No native support. This is a major limitation.
Use Case Examples - Scheduling an event for next Friday.
- Calculating a person's age.
- Logging an event with a full timestamp.
- Measuring how long a function takes to run (perf_counter()).
- Getting a unique ID based on time.
- Creating a simple delay (sleep()).

Bonus: The zoneinfo Module (Python 3.9+)

Time zones are crucial for any serious application. The datetime module itself doesn't handle time zones well, but Python 3.9 introduced the standard zoneinfo module, which is the modern way to do it.

Python time与datetime模块如何选择使用?-图3
(图片来源网络,侵删)
# Requires Python 3.9+
import datetime
import zoneinfo
# 1. Create a timezone-aware datetime object
# Let's get the current time in New York
ny_tz = zoneinfo.ZoneInfo("America/New_York")
now_in_ny = datetime.datetime.now(ny_tz)
print(f"Current time in New York: {now_in_ny}")
print(f"Timezone info: {now_in_ny.tzinfo}")
# 2. Convert between timezones
tokyo_tz = zoneinfo.ZoneInfo("Asia/Tokyo")
now_in_tokyo = now_in_ny.astimezone(tokyo_tz)
print(f"Current time in Tokyo: {now_in_tokyo}")

Summary and Recommendation

Use Case Recommended Module/Class
Get a simple, human-readable timestamp datetime.datetime.now().strftime(...) or time.ctime()
Measure elapsed time or performance time.perf_counter() (most precise)
Do any date math (add days, find difference) datetime.datetime + datetime.timedelta
Parse a date string from a file/API datetime.datetime.strptime(...)
Work with users in different time zones datetime + zoneinfo (Python 3.9+)
Create a unique ID based on time int(time.time())

For 95% of general date and time manipulation in Python, start with the datetime module. Only reach for the time module when you have a specific, low-level need that it fulfills better.

分享:
扫描分享到社交APP
上一篇
下一篇