Python 3.6中strptime()报错TypeError,无法转换字符串为datetime对象
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

