Python 来自字符串的日期时间不为';不匹配

Python 来自字符串的日期时间不为';不匹配,python,datetime,Python,Datetime,我试图从字符串中匹配特定的日期时间格式,但我收到一个ValueError,我不确定原因。我使用以下格式: t = datetime.datetime.strptime(t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time") 这是试图匹配以下字符串的操作: Nov 19, 2017 20:09:14.071360000 Eastern Standard Time 有人知道为什么这些不匹配吗?从中我们可以看到%f期望: 微秒作为十进制数字,在左边填充零

我试图从字符串中匹配特定的日期时间格式,但我收到一个
ValueError
,我不确定原因。我使用以下格式:

t = datetime.datetime.strptime(t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
这是试图匹配以下字符串的操作:

Nov 19, 2017 20:09:14.071360000 Eastern Standard Time
有人知道为什么这些不匹配吗?

从中我们可以看到
%f
期望:

微秒作为十进制数字,在左边填充零

字符串的问题是,右边有一个填充为零的数字

以下是解决问题的一种方法:

new_t = t.partition(" Eastern Standard Time")[0].rstrip('0') + ' Eastern Standard Time'
print(new_t)
#Nov 19, 2017 20:09:14.07136 Eastern Standard Time

t2 = datetime.datetime.strptime(new_t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
print(t2)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)
如和文档中所述,问题在于
%f
指令基本上被限制为微秒小数点后6位。虽然他们的解决方案可以很好地用于字符串,但如果字符串类似于

'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'
因为在这种情况下调用
rstrip('0')
不会将微秒缩短到合适的长度。否则,您可以对regex执行相同的操作:

import re
import datetime

date_string = 'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'
# use a regex to strip the microseconds to 6 decimal places:
new_date_string = ''.join(re.findall(r'(.*\.\d{6})\d+(.*)', date_string)[0])
print(new_date_string)
#'Nov 19, 2017 20:09:14.071360 Eastern Standard Time'

t = datetime.datetime.strptime(new_date_string,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")    
print(t)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)

你的解释比我的好+1。请看sacul的解释,它比我提供的解释更好。