You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

日期格式转换报错咨询:如何将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, so strptime can'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-%d which 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:09