日期格式转换报错咨询:如何将YYYY-MM-DD HH:MM:SS转为MM/DD/YYYY
Hey there, let's break down what's going wrong here and fix it step by step:
Core Issues Causing the Error
- Invalid non-date values in your data: The error message mentions
'Birth Dt'— this looks like a header string or invalid entry that doesn't match any date format, sostrptimecan't parse it. - Mismatched date format string: Your valid dates are in the format
1952-02-04 00:00:00(with hours/minutes/seconds), but your code uses%Y-%m-%dwhich only accounts for the date portion. Even valid dates would fail here.
Fixes You Can Implement
Option 1: Add Exception Handling to Skip Invalid Entries
Wrap your parsing logic in a try-except block to gracefully handle non-date values without crashing:
import datetime if clientDob is not None: try: # Update the format string to include time components clientDob = datetime.datetime.strptime(clientDob, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y') # Use '%m/%d/%y' if you want 2-digit years instead of 4-digit except ValueError: # Handle invalid entries: set to None, or keep the original string clientDob = None # Or replace with 'Invalid Date' if preferred
Option 2: Pre-Filter Valid Date Candidates First
If you can spot invalid entries upfront, add a quick check before parsing to avoid unnecessary exceptions:
import datetime if clientDob is not None and '-' in clientDob and len(clientDob) >= 10: try: clientDob = datetime.datetime.strptime(clientDob, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y') except ValueError: clientDob = None else: clientDob = None
Option 3: Handle Mixed Date Formats (If Needed)
If your dataset has both dates with time (1952-02-04 00:00:00) and without (1952-02-04), add a fallback parsing attempt:
import datetime if clientDob is not None: try: clientDob = datetime.datetime.strptime(clientDob, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y') except ValueError: try: clientDob = datetime.datetime.strptime(clientDob, '%Y-%m-%d').strftime('%m/%d/%Y') except ValueError: clientDob = None
内容的提问来源于stack exchange,提问作者user8128927
相关产品推荐
相关产品推荐

