Python中计算两种不同格式日期的天数差实现方法问询
The easiest solution here leverages Python's built-in datetime module—no external libraries required, which keeps things simple and reliable. Here's a step-by-step breakdown with code:
Step 1: Parse the Date Strings
Use datetime.strptime() to convert your string dates into datetime objects, matching the format codes to your input styles:
- For
YYYY/MM/DD: Use the format string"%Y/%m/%d" - For
YYYY/MM/DD HH:MM:SS: Use"%Y/%m/%d %H:%M:%S"
Step 2: Drop the Time Component
Call the .date() method on the datetime object that includes time—this converts it to a date type, which only stores year, month, and day (automatically discarding hours, minutes, seconds).
Step 3: Calculate the Difference
Subtract the two date objects to get a timedelta instance, then access its .days attribute to get the integer number of days between the dates. Use abs() to ensure a positive result regardless of which date is earlier.
Full Example Code
from datetime import datetime # Your sample dates date_without_time = "2024/05/10" date_with_time = "2024/05/15 14:30:00" # Parse and convert to date objects date1 = datetime.strptime(date_without_time, "%Y/%m/%d").date() date2 = datetime.strptime(date_with_time, "%Y/%m/%d %H:%M:%S").date() # Compute days difference days_between = abs(date2 - date1).days print(f"Days difference: {days_between}") # Output: 5
Automating for Multiple Pairs
If you need to handle this repeatedly, wrap the logic in a function that automatically detects the format (based on the presence of a space):
from datetime import datetime def get_days_between_dates(date_str1, date_str2): def parse_to_date(s): # Check if the string contains a time component if " " in s: return datetime.strptime(s, "%Y/%m/%d %H:%M:%S").date() else: return datetime.strptime(s, "%Y/%m/%d").date() d1 = parse_to_date(date_str1) d2 = parse_to_date(date_str2) return abs(d1 - d2).days # Test it out print(get_days_between_dates("2023/12/25", "2024/01/01 23:59:59")) # Output: 7
This approach is clean, efficient, and uses only Python's standard library—perfect for your use case where you want to ignore the time part and just get the day difference.
内容的提问来源于stack exchange,提问作者mitch

