杰瑞科技汇

Python日期字符串如何转换或处理?

Of course! Working with date strings is a very common task in Python. The most important thing to understand is the difference between a string (a piece of text) and a date object (a Python object that understands dates and times).

Python日期字符串如何转换或处理?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering the most common scenarios.


Parsing a Date String into a Date Object

This is the process of converting a string like "2025-10-27" into a proper Python datetime object. You do this with the datetime.strptime() method.

The key is to provide a format code that matches the structure of your date string.

Format Code Meaning Example
%Y Year with century 2025
%y Year without century (00-99) 23
%m Month as a zero-padded number 01 to 12
%B Month as full name January
%b Month as abbreviated name Jan
%d Day of the month 01 to 31
%H Hour (24-hour clock) 00 to 23
%I Hour (12-hour clock) 01 to 12
%M Minute 00 to 59
%S Second 00 to 59
%A Weekday as full name Friday
%p AM or PM AM or PM

Example: Basic Parsing

Let's parse the standard ISO 8601 format: "YYYY-MM-DD".

Python日期字符串如何转换或处理?-图2
(图片来源网络,侵删)
from datetime import datetime
date_string = "2025-10-27"
format_code = "%Y-%m-%d"
# Parse the string into a datetime object
date_object = datetime.strptime(date_string, format_code)
print(f"Original String: {date_string}")
print(f"Parsed Object:   {date_object}")
print(f"Type of object:  {type(date_object)}")
# Now you can access parts of the date easily
print(f"Year: {date_object.year}")
print(f"Month: {date_object.month}")
print(f"Day: {date_object.day}")

Output:

Original String: 2025-10-27
Parsed Object:   2025-10-27 00:00:00
Type of object:  <class 'datetime.datetime'>
Year: 2025
Month: 10
Day: 27

Example: Parsing Different Formats

from datetime import datetime
# Example 1: US Format with Month Name
date_str_1 = "October 27, 2025"
# %B for full month name, %d for day, %Y for year
dt1 = datetime.strptime(date_str_1, "%B %d, %Y")
print(f"Parsed: {dt1}") # Output: 2025-10-27 00:00:00
# Example 2: European Format with Time
date_str_2 = "27-10-2025 15:30"
# %d-%m-%Y for date, %H:%M for time
dt2 = datetime.strptime(date_str_2, "%d-%m-%Y %H:%M")
print(f"Parsed: {dt2}") # Output: 2025-10-27 15:30:00
# Example 3: Short Year with AM/PM
date_str_3 = "10/27/23 9:05 AM"
# %m/%d/%y for date, %I:%M %p for 12-hour time with AM/PM
dt3 = datetime.strptime(date_str_3, "%m/%d/%y %I:%M %p")
print(f"Parsed: {dt3}") # Output: 2025-10-27 09:05:00

Formatting a Date Object into a String

This is the reverse process. You have a datetime object and want to convert it into a specific string format. You use the .strftime() method on the object itself.

from datetime import datetime
# Create a datetime object
now = datetime.now()
# Format it into different string representations
# ISO 8601 format (standard)
iso_format = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"ISO Format: {iso_format}")
# US Format with Month Name
us_format = now.strftime("%B %d, %Y")
print(f"US Format: {us_format}")
# European Format
eu_format = now.strftime("%d.%m.%Y")
print(f"EU Format: {eu_format}")
# Short and Human-readable
readable_format = now.strftime("%a, %b %d, %Y")
print(f"Readable: {readable_format}")

Example Output (will vary based on current date):

ISO Format: 2025-10-27 10:30:55
US Format: October 27, 2025
EU Format: 27.10.2025
Readable: Fri, Oct 27, 2025

The Easy Way: The dateutil Parser

If your date string has a variable or non-standard format, writing the format code for strptime can be tedious. The python-dateutil library is fantastic for this.

Python日期字符串如何转换或处理?-图3
(图片来源网络,侵删)

First, install it:

pip install python-dateutil

Now you can parse many common formats automatically.

from dateutil import parser
# It can handle many different formats automatically!
date_strings = [
    "2025-10-27",
    "October 27, 2025",
    "27-Oct-2025",
    "20251027",  # Ambiguous, but makes a reasonable guess
    "10/27/2025",
    "2025-10-27T14:30:00" # ISO format with time
]
for date_str in date_strings:
    # parse() tries to figure out the format for you
    dt_object = parser.parse(date_str)
    print(f"'{date_str}'  -->  {dt_object} (Type: {type(dt_object)})")

Output:

'2025-10-27'  -->  2025-10-27 00:00:00 (Type: <class 'datetime.datetime'>)
'October 27, 2025'  -->  2025-10-27 00:00:00 (Type: <class 'datetime.datetime'>)
'27-Oct-2025'  -->  2025-10-27 00:00:00 (Type: <class 'datetime.datetime'>)
'20251027'  -->  2025-10-27 00:00:00 (Type: <class 'datetime.datetime'>)
'10/27/2025'  -->  2025-10-27 00:00:00 (Type: <class 'datetime.datetime'>)
'2025-10-27T14:30:00'  -->  2025-10-27 14:30:00 (Type: <class 'datetime.datetime'>)

Handling Time Zones (Important!)

For any serious application, you should use Python's built-in zoneinfo module (available in Python 3.9+) or the popular pytz library.

Using zoneinfo (Recommended for Python 3.9+)

from datetime import datetime
from zoneinfo import ZoneInfo
# Create a timezone-aware datetime object
# This represents the current time in New York
ny_time = datetime.now(ZoneInfo("America/New_York"))
print(f"New York Time: {ny_time}")
# Create a timezone-aware object from a string
date_string = "2025-10-27 15:00"
# First, parse it as a naive datetime
naive_dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M")
# Then, localize it to a timezone
aware_dt = naive_dt.replace(tzinfo=ZoneInfo("Europe/London"))
print(f"London Time:   {aware_dt}")
# You can convert between timezones
print(f"NY Time in UTC: {ny_time.astimezone(ZoneInfo('UTC'))}")

Summary: Which Method to Use?

Goal Best Method Why?
Parsing a standard format datetime.strptime(date_string, format_code) Fast, built-in, and precise. You control the exact format.
Parsing many formats dateutil.parser.parse(date_string) Flexible and convenient. Great for user input or log files.
Formatting a date object my_date_object.strftime(format_code) The standard way to convert a datetime object to a string.
Handling time zones zoneinfo (Python 3.9+) or pytz Essential for correctness in applications that span regions.
分享:
扫描分享到社交APP
上一篇
下一篇