杰瑞科技汇

Python time parse怎么用?

Of course! Parsing time in Python is a common task, and the primary tool for it is the datetime module. I'll guide you through the most common scenarios, from simple parsing to handling time zones and performance-critical applications.

Python time parse怎么用?-图1
(图片来源网络,侵删)

The Short Answer: The datetime.strptime Method

The most direct way to parse a string into a datetime object is using datetime.strptime() (string parse time). It works by specifying a format code that matches your input string.

from datetime import datetime
# Your time string
time_string = "2025-10-27 15:30:00"
# The format code: %Y=4-digit year, %m=2-digit month, %d=2-digit day, etc.
format_code = "%Y-%m-%d %H:%M:%S"
# Parse the string
dt_object = datetime.strptime(time_string, format_code)
print(f"Original string: {time_string}")
print(f"Parsed datetime object: {dt_object}")
print(f"Year: {dt_object.year}")
print(f"Month: {dt_object.month}")
print(f"Day: {dt_object.day}")
print(f"Hour: {dt_object.hour}")

Output:

Original string: 2025-10-27 15:30:00
Parsed datetime object: 2025-10-27 15:30:00
Year: 2025
Month: 10
Day: 27
Hour: 15

Common Format Codes

Here's a cheat sheet for the most common format codes used with strptime:

Code Meaning Example
%Y Year with century 2025
%y Year without century 23
%m Month as a zero-padded number 10
%B Full month name October
%b Abbreviated month name Oct
%d Day of the month 27
%H Hour (24-hour clock) 15
%I Hour (12-hour clock) 03
%M Minute 30
%S Second 00
%f Microsecond 000000
%A Full weekday name Friday
%p AM/PM designation PM
%Z Timezone name UTC
%z UTC offset in the form ±HHMM[SS[.ffffff]] +0000

Handling Different Time String Formats

No Time Part (Date Only)

If your string only has a date, use a format without time components.

Python time parse怎么用?-图2
(图片来源网络,侵删)
date_string = "2025/10/27"
format_code = "%Y/%m/%d"
dt_object = datetime.strptime(date_string, format_code)
print(dt_object)
# Output: 2025-10-27 00:00:00

Different Separators

Just match the separators in your format code.

# Using slashes and a 12-hour clock
time_string_12hr = "10/27/23 03:30 PM"
format_code_12hr = "%m/%d/%y %I:%M %p"
dt_object_12hr = datetime.strptime(time_string_12hr, format_code_12hr)
print(dt_object_12hr)
# Output: 2025-10-27 15:30:00

Including Timezone Information

If your string has a timezone name (like UTC or EST), strptime can parse it. However, it's often better to handle this manually for more control.

# With a timezone name
time_string_tz = "2025-10-27 15:30:00 EST"
format_code_tz = "%Y-%m-%d %H:%M:%S %Z"
dt_object_tz = datetime.strptime(time_string_tz, format_code_tz)
print(f"Parsed object with timezone name: {dt_object_tz}")
# Note: The tzinfo attribute will be set to a fixed-offset timezone.
# Output: 2025-10-27 15:30:00-05:00 (EST is typically UTC-5)

Parsing with Timezone Offsets (%z)

For timezone offsets like +0530 or -0800, use the %z code.

# With a timezone offset (+0530 means 5 hours 30 minutes ahead of UTC)
time_string_offset = "2025-10-27 15:30:00+0530"
format_code_offset = "%Y-%m-%d %H:%M:%S%z"
dt_object_offset = datetime.strptime(time_string_offset, format_code_offset)
print(f"Parsed object with offset: {dt_object_offset}")
# Output: 2025-10-27 15:30:00+05:30

When strptime Fails: The dateutil Alternative

The datetime.strptime method is strict. If the string doesn't match the format code exactly, it will raise a ValueError.

Python time parse怎么用?-图3
(图片来源网络,侵删)
# This will FAIL
messy_string = "October 27, 2025 at 3:30 PM"
# format_code = "%B %d, %Y at %I:%M %p" # This works, but what if the format changes?

For more flexible parsing, the best tool is the dateutil library. It's very good at guessing the format.

First, install it:

pip install python-dateutil

Now, use it:

from dateutil import parser
messy_string_1 = "October 27, 2025 at 3:30 PM"
messy_string_2 = "27-Oct-2025"
messy_string_3 = "20251027" # Ambiguous!
dt_1 = parser.parse(messy_string_1)
dt_2 = parser.parse(messy_string_2)
dt_3 = parser.parse(messy_string_3) # Guesses YYYYMMDD
print(f"Parsed 1: {dt_1}")
print(f"Parsed 2: {dt_2}")
print(f"Parsed 3: {dt_3}")

Output:

Parsed 1: 2025-10-27 15:30:00
Parsed 2: 2025-10-27 00:00:00
Parsed 3: 2025-10-27 00:00:00

Warning: dateutil.parser is powerful but can be slow and sometimes make incorrect guesses. Use it for user input or log files where the format is inconsistent, but stick to strptime for performance-critical or controlled data sources.


Performance: strptime vs. datetime.fromtimestamp

If you are parsing a timestamp that is a number of seconds (or milliseconds) since the "Epoch" (January 1, 1970), do not use strptime. It's much slower than using datetime.fromtimestamp().

import time
# A timestamp in seconds since the epoch
timestamp_seconds = 1698400200
# --- SLOW WAY (Don't do this) ---
timestamp_str = str(timestamp_seconds)
dt_slow = datetime.strptime(timestamp_str, "%s") # %s is not standard, just for example
print(f"Slow way: {dt_slow}")
# --- FAST WAY (Do this) ---
dt_fast = datetime.fromtimestamp(timestamp_seconds)
print(f"Fast way: {dt_fast}")

Output:

Slow way: 2025-10-27 15:30:00
Fast way: 2025-10-27 15:30:00

For milliseconds, divide by 1000.0:

timestamp_ms = 1698400200000
dt_ms = datetime.fromtimestamp(timestamp_ms / 1000.0)
print(f"From milliseconds: {dt_ms}")

Summary and Best Practices

Your Goal Recommended Method Why?
Parsing a string with a known format datetime.strptime(format_code, string) Fast, explicit, and reliable. The standard, idiomatic way.
Parsing a string with an unknown format dateutil.parser.parse(string) Flexible and handles many formats, but slower and less predictable.
Parsing a number (seconds since epoch) datetime.fromtimestamp(number) Extremely fast and the correct tool for this specific data type.
Parsing from an ISO 8601 string datetime.fromisoformat(string) (Python 3.7+) Built-in, fast, and standard for a very common format.
Working with time zones Use pytz or zoneinfo (Python 3.9+) library Timezone handling is complex. These libraries manage it correctly.
分享:
扫描分享到社交APP
上一篇
下一篇