杰瑞科技汇

Python 2.7中datetime模块如何正确使用?

Of course! Working with dates and times in Python 2.7 is primarily done using the built-in datetime module. While Python 3 has significant improvements, the core concepts in Python 2.7 are still very useful to understand.

Python 2.7中datetime模块如何正确使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide to the datetime module in Python 2.7.

The Basics: datetime, date, and time Objects

The datetime module contains several classes, but the most common ones are datetime, date, and time.

  • datetime.datetime: A combination of date and time.
  • datetime.date: Just a date (year, month, day).
  • datetime.time: Just a time (hour, minute, second, microsecond).

Creating Objects

You create these objects by calling their constructors.

import datetime
# --- Creating a datetime object ---
# Format: datetime.datetime(year, month, day, hour, minute, second, microsecond)
dt_now = datetime.datetime.now()
dt_specific = datetime.datetime(2025, 10, 26, 10, 30, 0)
print "Current datetime:", dt_now
print "Specific datetime:", dt_specific
print "-" * 20
# --- Creating a date object ---
# Format: datetime.date(year, month, day)
d_today = datetime.date.today()
d_specific = datetime.date(2025, 10, 26)
print "Today's date:", d_today
print "Specific date:", d_specific
print "-" * 20
# --- Creating a time object ---
# Format: datetime.time(hour, minute, second, microsecond)
t_specific = datetime.time(14, 30, 0)
print "Specific time:", t_specific

Accessing Attributes

Once you have an object, you can access its components using attributes.

Python 2.7中datetime模块如何正确使用?-图2
(图片来源网络,侵删)
dt = datetime.datetime(2025, 10, 26, 15, 45, 30)
print "Year:", dt.year
print "Month:", dt.month
print "Day:", dt.day
print "Hour:", dt.hour
print "Minute:", dt.minute
print "Second:", dt.second
print "Microsecond:", dt.microsecond

timedelta: For Date and Time Arithmetic

The timedelta class is used to represent a duration, the difference between two dates or times. You can use it to add or subtract time from a datetime object.

import datetime
# Create a specific datetime
now = datetime.datetime.now()
# Create a timedelta of 10 days
delta = datetime.timedelta(days=10)
# Add the timedelta to the datetime
future_date = now + delta
# Subtract the timedelta from the datetime
past_date = now - delta
print "Current datetime:", now
print "Date 10 days from now:", future_date
print "Date 10 days ago:", past_date
print "-" * 20
# You can also use weeks, days, hours, minutes, seconds, microseconds
delta_weeks = datetime.timedelta(weeks=2, hours=5)
future_date_weeks = now + delta_weeks
print "Date 2 weeks and 5 hours from now:", future_date_weeks

Formatting and Parsing Strings

A very common task is converting between datetime objects and human-readable strings.

Formatting (Object to String)

Use the strftime() method (string format time) to convert a datetime object into a string. You use format codes to specify the output.

Format Code Meaning Example
%Y Year with century 2025
%y Year without century 23
%m Month as a zero-padded decimal 10
%B Full month name October
%b Abbreviated month name Oct
%d Day of the month 26
%A Full weekday name Thursday
%a Abbreviated weekday name Thu
%H Hour (24-hour clock) 15
%I Hour (12-hour clock) 03
%M Minute 45
%S Second 30
%p AM/PM designation PM
import datetime
dt = datetime.datetime(2025, 10, 26, 15, 45, 30)
# Format 1: Standard ISO format
iso_format = dt.isoformat()
print "ISO Format:", iso_format
# Format 2: Custom format
custom_format = dt.strftime("%Y-%m-%d %H:%M:%S")
print "Custom Format (YYYY-MM-DD HH:MM:SS):", custom_format
# Format 3: More readable format
readable_format = dt.strftime("%B %d, %Y at %I:%M %p")
print "Readable Format:", readable_format

Parsing (String to Object)

Use the strptime() function (string parse time) to convert a string into a datetime object. The format string you provide must exactly match the input string.

Python 2.7中datetime模块如何正确使用?-图3
(图片来源网络,侵删)
import datetime
# The string to be parsed
date_string = "2025-10-26 15:45:30"
# The format string that matches the date_string
format_string = "%Y-%m-%d %H:%M:%S"
# Parse the string into a datetime object
parsed_dt = datetime.datetime.strptime(date_string, format_string)
print "Parsed object type:", type(parsed_dt)
print "Parsed datetime:", parsed_dt
print "Year from parsed object:", parsed_dt.year

Important Differences and Caveats in Python 2.7

datetime.utcnow() vs datetime.now()

  • datetime.now(): Returns the local date and time, including timezone information if the system is configured correctly (though the naive datetime object itself doesn't store the timezone).
  • datetime.utcnow(): Returns the current UTC (Coordinated Universal Time) as a naive datetime object. This is often preferred for logging, databases, or any application where you need a consistent, timezone-agnostic timestamp.
import datetime
# Local time
local_now = datetime.datetime.now()
print "Local time:", local_now
# UTC time
utc_now = datetime.datetime.utcnow()
print "UTC time:", utc_now

Time Zones (A Major Limitation in Python 2.7)

The built-in datetime module has very limited support for timezones. A datetime object created with now() or utcnow() is called "naive" because it doesn't contain any timezone information.

To handle timezones properly in Python 2.7, you almost always need to use a third-party library. The most common one is pytz.

Example using pytz:

First, you need to install it: pip install pytz

import datetime
import pytz
# 1. Create a naive datetime
naive_dt = datetime.datetime(2025, 10, 26, 12, 0, 0)
print "Naive datetime:", naive_dt
# 2. Create a timezone-aware datetime in UTC
# First, get the UTC timezone object from pytz
utc_tz = pytz.utc
# Then, localize the naive datetime
aware_dt_utc = utc_tz.localize(naive_dt)
print "UTC Aware datetime:", aware_dt_utc
# 3. Convert the UTC datetime to another timezone (e.g., US/Eastern)
eastern_tz = pytz.timezone('US/Eastern')
aware_dt_eastern = aware_dt_utc.astimezone(eastern_tz)
print "US/Eastern Aware datetime:", aware_dt_eastern

Summary

Task Python 2.7 Code (using datetime module) Notes
Get current datetime datetime.datetime.now() Returns a "naive" local datetime.
Get current UTC datetime datetime.datetime.utcnow() Returns a "naive" UTC datetime. Preferred for consistency.
Create a specific datetime datetime.datetime(2025, 10, 26, 15, 30)
Create a date datetime.date(2025, 10, 26)
Add/Subtract time my_datetime + datetime.timedelta(days=1) Use timedelta for arithmetic.
Format datetime to string my_datetime.strftime("%Y-%m-%d") Use strftime() with format codes.
Parse string to datetime datetime.datetime.strptime("2025-10-26", "%Y-%m-%d") Use strptime() with a matching format string.
Handle Timezones Not natively supported. Use pytz library. pytz.utc.localize() and .astimezone() are essential functions.
分享:
扫描分享到社交APP
上一篇
下一篇