带有可选位的python strptime格式

Dig*_*dra 40 python datetime-format

现在我有:

timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)

除非我转换一个没有微秒的字符串,否则这很有效.如何指定微秒是可选的(如果它们不在字符串中,则应该被视为0)?

Ale*_*der 42

你可以使用一个try/except块:

try:
    timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
    timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

  • 有点遗憾的是,这依赖于[异常作为控制流](https://www.reddit.com/r/Python/comments/ixkfqd/exceptions_as_control_flow/)。 (2认同)
  • @JoeSadoski 我不认为上面的解决方案符合您链接的文章中描述的内容。 (2认同)

ste*_*ieb 16

如果不存在,只需附加它怎么样?

if '.' not in date_string:
    date_string = date_string + '.0'

timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,但令我失望的是,一个旨在将头痛的人从将日期和时间字符串转换为日期和时间对象的库无法处理这些非常简单的用例。这样的库的全部目的是消除用户的担心。 (3认同)
  • 我非常喜欢这个答案,而不是使用try / catch (2认同)

fou*_*xes 5

我更喜欢使用正则表达式匹配而不是尝试和除外。这允许许多可接受格式的回退。

# full timestamp with milliseconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z", date_string)
if match:
    return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")

# timestamp missing milliseconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", date_string)
if match:
    return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%SZ")

# timestamp missing milliseconds & seconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z", date_string)
if match:
    return datetime.strptime(date_string, "%Y-%m-%dT%H:%MZ")

# unknown timestamp format
return false
Run Code Online (Sandbox Code Playgroud)

不要忘记为此方法导入“re”和“datetime”。


小智 5

我迟到了,但我发现如果你不关心可选位,这会为你去掉 .%f 。

datestring.split('.')[0]