Python日期时间Strptime错误:'-'是格式'%-m-%-d-%y %-H:%M:%S'的错误指令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41191365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:32:31  来源:igfitidea点击:

Python Datetime Strptime Error: '-' is a bad directive in format '%-m-%-d-%y %-H:%M:%S'

pythondatetime

提问by slearner

I know that there have been similar questions asked, but they seemed to have to do with the way datetime deals (or doesn't deal) with timezones.

我知道有人问过类似的问题,但它们似乎与日期时间处理(或不处理)时区的方式有关。

The setup is a little complicated, and probably not relevant to the problem, but I thought it was important to include the code as is, so a little background:

设置有点复杂,可能与问题无关,但我认为按原样包含代码很重要,所以有点背景:

I've got a dictionary of arrays. Each of these arrays represents an "attempt" by the same person, but taking place at different times. Ultimately I'm going to be looking for the earliest of these dates. This may be a bit of a roundabout solution, but I'm converting all of the dates to datetime objects, finding the earliest and then just using that index to pull out the first attempt:

我有一个数组字典。这些数组中的每一个都代表同一个人的“尝试”,但发生在不同的时间。最终,我将寻找这些日期中最早的日期。这可能有点迂回解决方案,但我将所有日期转换为 datetime 对象,找到最早的,然后只使用该索引来提取第一次尝试:

Here's what the code looks like to setup that array of attempt datetimes:

以下是设置该尝试日期时间数组的代码:

for key in duplicates_set.keys():
    attempt_dates = [datetime.strptime(attempt['Attempt Date'], "%-m-%-d-%y %-H:%M:%S") for attempt in duplicates_set[key]]

Here's the format of what one of the original date strings looks like:

这是原始日期字符串之一的格式:

12-5-2016 3:27:58 PM

12-5-2016 3:27:58 PM

What I'm getting back is:

我要回来的是:

ValueError: '-' is a bad directive in format '%-m-%d-%y %-H:%M:%S'

I assume that's referring to the dashes placed before the 'm', 'd' and 'H' because they're non-zero-padded decimals. Why is it telling me that?

我认为这是指放置在“m”、“d”和“H”之前的破折号,因为它们是非零填充小数。为什么要这样告诉我?

回答by Charles Duffy

%-*-- to skip padding -- is a GNU libc extension. It's not part of POSIX strftime, and thus not guaranteed to be portable to systems where your time-formatting calls aren't eventually backed by GNU's strftimeC library function.

%-*-- 跳过填充 -- 是 GNU libc 扩展。它不是 POSIX strftime 的一部分,因此不能保证可移植到您的时间格式化调用最终不受 GNU 的strftimeC 库函数支持的系统。

The Python datetimemodule documentationexplicitly specifies the format strings it supports, and this extension is not given. Thus, while this is supported in GNU date and GNU strftime(), it isn't available in Python datetime.

Pythondatetime模块文档明确指定了它支持的格式字符串,并且没有给出这个扩展。因此,虽然这在 GNU date 和 GNU 中受支持strftime(),但在 Python 中不可用datetime