Python匹配自定义日期格式:提取后无法转为datetime对象问题
2018.02.09_11.34.09 Format Hey there! Let's figure out why your datetime conversion is failing—it's almost always a format string mismatch, so let's break this down step by step:
1. Fix your format string (the #1 culprit)
Your date string follows the pattern YYYY.MM.DD_HH.MM.SS, which means your format code needs to exactly match every character, including dots and underscores.
A lot of folks slip up here: using slashes instead of dots, forgetting the underscore, or mixing up format codes (like using %m for minutes instead of %M—remember, %m is for months, %M is for minutes!).
Here's the correct code to convert your string:
from datetime import datetime extracted_date = "2018.02.09_11.34.09" try: dt_object = datetime.strptime(extracted_date, "%Y.%m.%d_%H.%M.%S") print(dt_object) # Output: 2018-02-09 11:34:09 except ValueError as e: print(f"Conversion error: {e}")
2. Check for hidden characters in your extracted string
Sometimes when pulling the date from a larger string, you might accidentally grab invisible characters (like leading/trailing spaces, tabs, or newlines) that break the format. To verify, print the "raw" representation of your string using repr():
print(repr(extracted_date))
If you see extra characters (e.g., ' 2018.02.09_11.34.09' with leading spaces), clean the string first with strip():
cleaned_date = extracted_date.strip() dt_object = datetime.strptime(cleaned_date, "%Y.%m.%d_%H.%M.%S")
3. Double-check format code definitions
Just to be thorough, confirm you're using the right codes for each part:
%Y: 4-digit year (e.g., 2018)%m: 2-digit month (01-12)%d: 2-digit day (01-31)%H: 24-hour format hour (00-23)%M: 2-digit minute (00-59)%S: 2-digit second (00-59)
Using the wrong code (like %y for 2-digit year instead of %Y) will throw a ValueError too.
内容的提问来源于stack exchange,提问作者shikhanshu

