字符串的日期时间不匹配

时间:2018-03-23 20:18:12

标签: 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

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

2 个答案:

答案 0 :(得分:5)

docs我们可以看到%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)

答案 1 :(得分:2)

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)