t=datetime.datetime.strptime("2021/5/12 09:28:11",format="%Y/%m/%d %h:%m:%s")

1.错误原因:参数格式不匹配

_strptime定义:

def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):"""Return a 2-tuple consisting of a time struct and an int containingthe number of microseconds based on the input string and theformat string."""for index, arg in enumerate([data_string, format]):if not isinstance(arg, str):msg = "strptime() argument {} must be str, not {}"raise TypeError(msg.format(index, type(arg)))global _TimeRE_cache, _regex_cachewith _cache_lock:locale_time = _TimeRE_cache.locale_timeif (_getlang() != locale_time.lang ortime.tzname != locale_time.tzname ortime.daylight != locale_time.daylight):_TimeRE_cache = TimeRE()_regex_cache.clear()locale_time = _TimeRE_cache.locale_timeif len(_regex_cache) > _CACHE_MAX_SIZE:_regex_cache.clear()format_regex = _regex_cache.get(format)if not format_regex:try:format_regex = _TimeRE_cache.compile(format)# KeyError raised when a bad format is found; can be specified as# \\, in which case it was a stray % but with a space after itexcept KeyError as err:bad_directive = err.args[0]if bad_directive == "\\":bad_directive = "%"del errraise ValueError("'%s' is a bad directive in format '%s'" %(bad_directive, format)) from None# IndexError only occurs when the format string is "%"except IndexError:raise ValueError("stray %% in format '%s'" % format) from None_regex_cache[format] = format_regexfound = format_regex.match(data_string)if not found:raise ValueError("time data %r does not match format %r" %(data_string, format))if len(data_string) != found.end():raise ValueError("unconverted data remains: %s" %data_string[found.end():])iso_year = year = Nonemonth = day = 1hour = minute = second = fraction = 0tz = -1gmtoff = Nonegmtoff_fraction = 0# Default to -1 to signify that values not known; not critical to have,# thoughiso_week = week_of_year = Noneweek_of_year_start = None# weekday and julian defaulted to None so as to signal need to calculate# valuesweekday = julian = Nonefound_dict = found.groupdict()for group_key in found_dict.keys():# Directives not explicitly handled below:#   c, x, X#      handled by making out of other directives#   U, W#      worthless without day of the weekif group_key == 'y':year = int(found_dict['y'])# Open Group specification for strptime() states that a %y#value in the range of [00, 68] is in the century 2000, while#[69,99] is in the century 1900if year <= 68:year += 2000else:year += 1900elif group_key == 'Y':year = int(found_dict['Y'])elif group_key == 'G':iso_year = int(found_dict['G'])elif group_key == 'm':month = int(found_dict['m'])elif group_key == 'B':month = locale_time.f_month.index(found_dict['B'].lower())elif group_key == 'b':month = locale_time.a_month.index(found_dict['b'].lower())elif group_key == 'd':day = int(found_dict['d'])elif group_key == 'H':hour = int(found_dict['H'])elif group_key == 'I':hour = int(found_dict['I'])ampm = found_dict.get('p', '').lower()# If there was no AM/PM indicator, we'll treat this like AMif ampm in ('', locale_time.am_pm[0]):# We're in AM so the hour is correct unless we're# looking at 12 midnight.# 12 midnight == 12 AM == hour 0if hour == 12:hour = 0elif ampm == locale_time.am_pm[1]:# We're in PM so we need to add 12 to the hour unless# we're looking at 12 noon.# 12 noon == 12 PM == hour 12if hour != 12:hour += 12elif group_key == 'M':minute = int(found_dict['M'])elif group_key == 'S':second = int(found_dict['S'])elif group_key == 'f':s = found_dict['f']# Pad to always return microseconds.s += "0" * (6 - len(s))fraction = int(s)elif group_key == 'A':weekday = locale_time.f_weekday.index(found_dict['A'].lower())elif group_key == 'a':weekday = locale_time.a_weekday.index(found_dict['a'].lower())elif group_key == 'w':weekday = int(found_dict['w'])if weekday == 0:weekday = 6else:weekday -= 1elif group_key == 'u':weekday = int(found_dict['u'])weekday -= 1elif group_key == 'j':julian = int(found_dict['j'])elif group_key in ('U', 'W'):week_of_year = int(found_dict[group_key])if group_key == 'U':# U starts week on Sunday.week_of_year_start = 6else:# W starts week on Monday.week_of_year_start = 0elif group_key == 'V':iso_week = int(found_dict['V'])elif group_key == 'z':z = found_dict['z']if z == 'Z':gmtoff = 0else:if z[3] == ':':z = z[:3] + z[4:]if len(z) > 5:if z[5] != ':':msg = f"Inconsistent use of : in {found_dict['z']}"raise ValueError(msg)z = z[:5] + z[6:]hours = int(z[1:3])minutes = int(z[3:5])seconds = int(z[5:7] or 0)gmtoff = (hours * 60 * 60) + (minutes * 60) + secondsgmtoff_remainder = z[8:]# Pad to always return microseconds.gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)if z.startswith("-"):gmtoff = -gmtoffgmtoff_fraction = -gmtoff_fractionelif group_key == 'Z':# Since -1 is default value only need to worry about setting tz if# it can be something other than -1.found_zone = found_dict['Z'].lower()for value, tz_values in enumerate(locale_time.timezone):if found_zone in tz_values:# Deal with bad locale setup where timezone names are the# same and yet time.daylight is true; too ambiguous to# be able to tell what timezone has daylight savingsif (time.tzname[0] == time.tzname[1] andtime.daylight and found_zone not in ("utc", "gmt")):breakelse:tz = valuebreak# Deal with the cases where ambiguities arize# don't assume default values for ISO week/yearif year is None and iso_year is not None:if iso_week is None or weekday is None:raise ValueError("ISO year directive '%G' must be used with ""the ISO week directive '%V' and a weekday ""directive ('%A', '%a', '%w', or '%u').")if julian is not None:raise ValueError("Day of the year directive '%j' is not ""compatible with ISO year directive '%G'. ""Use '%Y' instead.")elif week_of_year is None and iso_week is not None:if weekday is None:raise ValueError("ISO week directive '%V' must be used with ""the ISO year directive '%G' and a weekday ""directive ('%A', '%a', '%w', or '%u').")else:raise ValueError("ISO week directive '%V' is incompatible with ""the year directive '%Y'. Use the ISO year '%G' ""instead.")leap_year_fix = Falseif year is None and month == 2 and day == 29:year = 1904  # 1904 is first leap year of 20th centuryleap_year_fix = Trueelif year is None:year = 1900# If we know the week of the year and what day of that week, we can figure# out the Julian day of the year.if julian is None and weekday is not None:if week_of_year is not None:week_starts_Mon = True if week_of_year_start == 0 else Falsejulian = _calc_julian_from_U_or_W(year, week_of_year, weekday,week_starts_Mon)elif iso_year is not None and iso_week is not None:year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1)if julian is not None and julian <= 0:year -= 1yday = 366 if calendar.isleap(year) else 365julian += ydayif julian is None:# Cannot pre-calculate datetime_date() since can change in Julian# calculation and thus could have different value for the day of# the week calculation.# Need to add 1 to result since first day of the year is 1, not 0.julian = datetime_date(year, month, day).toordinal() - \datetime_date(year, 1, 1).toordinal() + 1else:  # Assume that if they bothered to include Julian day (or if it was# calculated above with year/week/weekday) it will be accurate.datetime_result = datetime_date.fromordinal((julian - 1) +datetime_date(year, 1, 1).toordinal())year = datetime_result.yearmonth = datetime_result.monthday = datetime_result.dayif weekday is None:weekday = datetime_date(year, month, day).weekday()# Add timezone infotzname = found_dict.get("Z")if leap_year_fix:# the caller didn't supply a year but asked for Feb 29th. We couldn't# use the default of 1900 for computations. We set it back to ensure# that February 29th is smaller than March 1st.year = 1900return (year, month, day,hour, minute, second,weekday, julian, tz, tzname
def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):"""Return a time struct based on the input string and theformat string."""tt = _strptime(data_string, format)[0]return time.struct_time(tt[:time._STRUCT_TM_ITEMS])def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):"""Return a class cls instance based on the input string and theformat string."""tt, fraction, gmtoff_fraction = _strptime(data_string, format)tzname, gmtoff = tt[-2:]args = tt[:6] + (fraction,)if gmtoff is not None:tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)if tzname:tz = datetime_timezone(tzdelta, tzname)else:tz = datetime_timezone(tzdelta)args += (tz,)return cls(*args)

调用的时候,增加了格式限制,不能使用关键字参数,只能使用位置参数

2.解决方法

去掉关键字"format=",这时候再次运行,会出现新错误:

ValueError("'%s' is a bad directive in format '%s'" %
ValueError: 'h' is a bad directive in format '%Y/%m/%d %h:%m:%s'

提示ValueError,format的格式问题

改为:t=datetime.datetime.strptime("2021/5/12 09:28:11","%Y/%m/%d %H:%M:%S"),正常运行

TypeError: strptime() takes no keyword arguments ValueError(“‘%s‘ is a bad directive in format ‘%s‘“相关推荐

  1. MNE-Python : TypeError: today() takes no keyword arguments

    运行代码 在使用MNE读取gdf文件时 import mne %matplotlib inline# Mention the file path to the dataset path = " ...

  2. Python使用字典get()方法TypeError: get() takes no keyword arguments

    解决方法 dict的get("key", 0)方法不要添加default=,删除这个写法并不影响使用逻辑,但是加上会导致报错. d = {'key': 2, } print(d.g ...

  3. 关于 - TypeError: dict.get() takes no keyword arguments

    首先我们来看一下关于 dict 的 get() 函数的使用方法 get 函数的用法:dict.get(key, default=None) , key 为需要获取 value 的 key,defaul ...

  4. python创建对象后调用对象的方法,报错TypeError: getName() takes 0 positional arguments but 1 was given

    源码 ## TODO: Create multiple cars and visualize them height = 4 width = 6 world = np.zeros((height, w ...

  5. 成功解决TypeError: fit_transform() takes 2 positional arguments but 3 were given

    成功解决Traceback (most recent call last):   File "F:\Program Files\Python\Python36\lib\site-packag ...

  6. OpenCV——解决使用rectangle()函数时出现“TypeError: function takes exactly 4 arguments (2 given)”错误

    1 问题描述 今天在使用cv.rectangle()函数时,出现了这样的报错: TypeError: function takes exactly 4 arguments (2 given) 源代码我 ...

  7. TypeError: __init__() takes exactly 2 arguments (3 given)

    TypeError: __init__() takes exactly 2 arguments (3 given) 意思是说,该方法只有两个参数,你却给他3个:

  8. TypeError: classification_report() takes 2 positional arguments but 3 were given的解决方案

      大家好,我是爱编程的喵喵.双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中.从事机器学习以及相关的前后端开发工作.曾在阿里云.科大讯飞.CCF等比赛获得多次Top名次.喜 ...

  9. 解决TypeError: set_ticks() takes 2 positional arguments but 3 were given

    其他问题参考: Python基础-TypeError:takes 2 positional arguments but 3 were given https://blog.csdn.net/weixi ...

最新文章

  1. JSP学习笔记(七):使用JavaBean
  2. 结构体内指针数组调用_指针的这些技巧你都掌握了吗
  3. Ubuntu 12.04下PostgreSQL-9.1安装与配置详解(在线安装)
  4. kde Plasmoid Applet开发
  5. C二维数组行为空,列不为空
  6. win7下的iis配置
  7. (转)完全使用gnu/linux工作
  8. DELPHI参数几个概念上的区别 收藏
  9. 【Redis】14.Redis高级数据类型Bitmaps、HyperLogLog、GEO
  10. Block CONNECT method in httpd.conf
  11. 028-Dell服务器做Raid
  12. ES6新特性_ES6生成器函数声明与调用---JavaScript_ECMAScript_ES6-ES11新特性工作笔记020
  13. drupal7 smtp+mimemail+mailsystem 实现发送html邮件
  14. doip 源码_DoIP—协议框架
  15. 这些安全管理方法,让你不怕勒索者
  16. BLDC电机中的死区时间究竟是什么?
  17. 神经网络与BP算法(代码实现)
  18. Python编程:itertools库排列组合
  19. 美团——大众测试开发工程师校招
  20. 英语学习——Kaizen

热门文章

  1. 自动添加控件,一次提交多条记录。
  2. 苹果:用Impactor安装软件时出现Line:182错误
  3. 【友情链接NO.0000?】大佬们的博客(°ー°〃)
  4. ${}和`${}`的用法
  5. linux svn 查看忽略文件
  6. 强化学习适合解决什么样的问题
  7. python中函数返回值为func 和func() 的区别
  8. [198].打家劫舍
  9. ? ? 与 || 的区别
  10. 楼道灯人体红外感应电路(半波式)