使用正则表达式获取日期和时间

我正在尝试从字符串中提取日期和时间,建立该字符串与当前日期和时间之间的增量。我尝试将正则表达式输出从列表转换为字符串,它显示为 type=string 但格式如下 - ('18:06:39', 'Jan 30 2020')。


import re

from datetime import datetime, timedelta, date


string = 'configuration change at 18:06:39 EET Thu Jan 30 2020 by netbrain'

chg_date = re.findall(r"(\d{2}:\d{2}:\d{2}) \w+ \w+ (\w{3} \d{2} \d{4})", string)

chg_date_str = ''.join(map(str, chg_date))

now = datetime.now()

now_format = now.strftime("%H:%M:%S, %b %d %y")

time_difference = now_format - chg_date_str

print(chg_date_str)

print(time_difference)

我收到以下错误。


Traceback (most recent call last):

  File "C:/Users/MattSherman/Desktop/Python/y.py", line 15, in <module>

    time_difference = now_format - chg_date_str

TypeError: unsupported operand type(s) for -: 'str' and 'str'


慕姐8265434
浏览 107回答 3
3回答

莫回无

如果要计算时间增量,则需要对datetime实例进行算术运算。您可以使用如下所示的函数将结果转换findall()为 a :datetimedatetime.strptime()import refrom datetime import datetime, timedelta, datestring = 'configuration change at 18:06:39 EET Thu Jan 30 2020 by netbrain'matches = re.findall(r"(\d{2}:\d{2}:\d{2}) \w+ \w+ (\w{3} \d{2} \d{4})", string)chg_date_str = ' '.join(map(str, matches[0]))chg_date = datetime.strptime(chg_date_str, "%H:%M:%S %b %d %Y")now = datetime.now()time_difference = now - chg_dateprint(chg_date_str)print(time_difference)输出:18:06:39 Jan 30 20205 days, 16:34:32.661231

qq_遁去的一_1

你的代码有很多问题。findall返回元组列表。您应该迭代findall结果或使用search而不是findall您使用 连接部分数据'',但您需要' '%y是 4 位数年份的错误模式,应该使用%Y您将日期转换为字符串并尝试找出两个字符串之间的差异...我认为你的代码应该是这样的:import refrom datetime import datetimestring = 'configuration change at 18:06:39 EET Thu Jan 30 2020 by netbrain'chg_dates = re.findall(r"(\d{2}:\d{2}:\d{2}) \w+ \w+ (\w{3} \d{2} \d{4})", string)for chg_date in chg_dates:&nbsp; &nbsp; chg_date_str = ' '.join(map(str, chg_date))&nbsp; &nbsp; chg_date_date = datetime.strptime(chg_date_str, "%H:%M:%S %b %d %Y")&nbsp; &nbsp; now = datetime.now()&nbsp; &nbsp; time_difference = now - chg_date_date&nbsp; &nbsp; print(time_difference)

猛跑小猪

其他人回答了它,但有两个主要问题。您试图从彼此减去 2 个字符串,python 不能这样做,而是您应该减去 2 个 datetime 对象。此外,re.findall()返回一个长度为 1 的列表,因此当连接chg_date到 a时,chg_date_str您实际上必须连接返回列表中的第 0 个项目,即chg_date_str[0]. 如果您使用 a', '而不是空字符串连接,它看起来也更干净,当然,相应地更新 datetime 参数。import refrom datetime import datetime, timedelta, datestring = 'configuration change at 18:06:39 EET Thu Jan 30 2020 by netbrain'chg_date = re.findall(r"(\d{2}:\d{2}:\d{2}) \w+ \w+ (\w{3} \d{2} \d{4})", string)chg_date_str = ', '.join(map(str, chg_date[0]))datetime_object = datetime.strptime(chg_date_str, '%H:%M:%S, %b %d %Y')time_difference = datetime.now() - datetime_objectprint(chg_date_str)print(time_difference)输出:18:06:39, Jan 30 20205 days, 19:05:05.272112我相信这就是你想要的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python