ValueError: time data '2021-07-28 10:27:51,834' does not match format '&Y-%m-%d %H:%M:%S,%f'

ValueError: time data '2021-07-28 10:27:51,834' does not match format '&Y-%m-%d %H:%M:%S,%f'

谁能看看这里的时间格式有什么问题吗?

获取:

ValueError: 时间数据 '2021-07-28 10:27:51,834' 不匹配格式 '&Y-%m-%d %H:%M:%S,%f'

在这里使用:

import re
from time import strptime

time_short = re.compile(r"(\d+-\d+-\d+ \d+:\d+:\d+,\d+)")
t_fmt = '&Y-%m-%d %H:%M:%S,%f'
with open(r'output\output.txt', 'r+') as file:
   lines = file.readlines()
   for i in sorted(lines, key=lambda i: strptime(time_short.search(i).group(1), t_fmt)):
      print(i)

文件将如下所示:

2021-07-28 10:27:49,869 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following> 
2021-07-28 10:27:49,881 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following> 
2021-07-28 10:27:51,834 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following> 
2021-07-28 10:27:52,182 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following>

也许有什么想法?感谢您的任何建议!


2021 年 9 月 8 日编辑


非常感谢您的帮助,这么无聊的问题。抱歉,添麻烦了。 但是在修正时间格式后又出现了一个问题

import re
from time import strptime

time_short = re.compile(r"(\d+-\d+-\d+ \d+:\d+:\d+,\d+)")
t_fmt = '%Y-%m-%d %H:%M:%S,%f'
with open(r'output\output.txt', 'r+') as file:
   lines = file.readlines()
   for i in sorted(lines, key=lambda i: strptime(time_short.search(i).group(1), t_fmt)):
      print(i)

但我仍然收到未排序的数据,例如:


2021-07-28 10:27:51,834 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following>
2021-07-28 10:27:49,869 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following> 
2021-07-28 10:27:52,182 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT <xml code following></xml code following>
2021-07-28 10:27:49,881 qwer123 instanceA 10.10.10.1 aaaaa/111 ABC DEFAULT<xml code following></xml code following>   

有什么建议吗?

您的代码中有一个小错字。 只是改变

t_fmt = '&Y-%m-%d %H:%M:%S,%f'

t_fmt = '%Y-%m-%d %H:%M:%S,%f'

当我 运行 代码时,排序似乎有效,但不适用于微秒。请记住,time.strptime 不适用于微秒,您必须使用 datetime.strptime .

您可以在这里尝试: https://www.online-python.com/5LZhoAljfR

import re
from time import strptime
from datetime import datetime

time_short = re.compile(r"(\d+-\d+-\d+ \d+:\d+:\d+,\d+)")
t_fmt = '%Y-%m-%d %H:%M:%S,%f'

lines=[
"2021-07-28 10:20:30,100 aaa>",
"2021-07-28 10:21:30,200 bbb>",
"2021-07-28 10:20:30,400 ccc>",
"2021-07-28 10:20:30,300 ddd>",
"2021-07-28 10:20:30,500 eee>"]

for i in sorted(lines, key=lambda i: datetime.strptime(time_short.search(i).group(1), t_fmt)):
    print(i)