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

Python 3.6中strptime()报错TypeError,无法转换字符串为datetime对象

Fixing TypeError: strptime() takes no keyword arguments in Python 3.6

Ah, I see the issue here! The datetime.datetime.strptime() method doesn’t accept keyword arguments for its parameters—even though the argument is named format in the documentation, you have to pass it as a positional argument instead of using format=.

Here’s why: Many of Python’s built-in datetime methods (including strptime) are implemented in C for performance, and they don’t support keyword argument syntax for their parameters. So when you try to pass format="%Y-%m-%d" as a keyword argument, Python throws that TypeError because the method doesn’t recognize the keyword.

Corrected Code

Just remove the format= part and pass the format string as the second positional argument:

import datetime
datetime.datetime.strptime("2018-04-02", "%Y-%m-%d")

This will work perfectly and return the expected datetime object: datetime.datetime(2018, 4, 2, 0, 0).

Quick Tip for Clarity

If you prefer using keyword arguments for readability (totally reasonable!), you can wrap the built-in method in a small helper function:

import datetime

def strptime_with_kw(date_str, format):
    return datetime.datetime.strptime(date_str, format)

# Now you can use keyword arguments
strptime_with_kw("2018-04-02", format="%Y-%m-%d")

But for the native strptime() method itself, positional arguments are the required approach here.

内容的提问来源于stack exchange,提问作者user8270077

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:32:12