如何在Python中将时间字符串"20180425.142117"转为人类易读格式?
Got it, let's break down how to turn your timestamp string 20180425.142117 into a friendly format like 25th April 2018, 2:21 pm in Python. Here's a complete, easy-to-follow solution:
Step 1: Parse the Raw Timestamp
First, we need to convert the string into a datetime object using datetime.strptime(). This function lets us define exactly how the input string is structured so Python can interpret it correctly.
Step 2: Add Ordinal Suffixes (st/nd/rd/th)
Python's built-in formatting doesn't handle ordinal suffixes automatically, so we'll write a small helper function to generate them correctly—this includes edge cases like 11th, 12th, and 13th, which don't follow the standard digit-to-suffix rule.
Step 3: Format to the Target String
Once we have the datetime object, we can extract and format each component (day with suffix, month name, year, 12-hour time) into the final human-readable string.
Full Code Example
from datetime import datetime def get_ordinal(day): """Return the day with its ordinal suffix (e.g., 25 → 25th)""" if 11 <= day <= 13: return f"{day}th" last_digit = day % 10 suffix_map = {1: "st", 2: "nd", 3: "rd"} return f"{day}{suffix_map.get(last_digit, 'th')}" # Your input timestamp raw_timestamp = "20180425.142117" # Parse the string into a datetime object parsed_dt = datetime.strptime(raw_timestamp, "%Y%m%d.%H%M%S") # Build the formatted string ordinal_day = get_ordinal(parsed_dt.day) # Format time to 12-hour format, removing leading zero from hour formatted_time = parsed_dt.strftime("%I:%M %p").lstrip('0').lower() final_result = f"{ordinal_day} {parsed_dt.strftime('%B %Y')}, {formatted_time}" print(final_result) # Output: 25th April 2018, 2:21 pm
Key Details:
- Parsing: The format string
"%Y%m%d.%H%M%S"matches your input perfectly:%Y(4-digit year),%m(2-digit month),%d(2-digit day), followed by a dot, then%H(24-hour hour),%M(minutes),%S(seconds). - Ordinal Suffixes: The helper function first checks for the 11-13 exception, then uses a dictionary to map single digits to their correct suffixes—falling back to "th" for all other cases.
- Time Formatting:
%Igives the 12-hour hour (with a leading zero for values 1-9), so we uselstrip('0')to clean that up. The.lower()convertsPMtopmto match your example; remove it if you prefer uppercasePM.
内容的提问来源于stack exchange,提问作者AS_ON

