python – 字符串的日期时间不匹配

我试图匹配字符串中的特定日期时间格式,但我收到一个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

任何人都可以看到为什么这些不匹配?

最佳答案 正如
pault和文档所述,问题是%f指令基本上限制为微秒的6位小数.虽然他们的解决方案适用于您的字符串,但如果您的字符串类似,则可能会出现问题

'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'

因为在这种情况下调用rstrip(‘0’)不会将微秒缩短到适当的长度.否则你可以用正则表达式做同样的事情:

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)
点赞