python re模块实例记录
匹配字符串中的日期时间
import json
if __name__ == '__main__':
import re
import datetime
s = {"siteID": "123",
"msgTime": "2022-08-05 13:12:33",
"floorID": "",
"beginTime": "2022-08-05 13:12:33",}
ctime_s = datetime.datetime.now()
ctime = datetime.datetime.strftime(ctime_s, "%Y-%m-%d %H:%M:%S")
s = json.dumps(s)
p = re.compile(r'(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2})').findall(s)
print(p)
结果:
替换字符串中的日期时间
import json
if __name__ == '__main__':
import re
import datetime
s = {"siteID": "123",
"msgTime": "2022-08-05 13:12:33",
"floorID": "",
"beginTime": "2022-08-05 13:12:33",}
ctime_s = datetime.datetime.now()
ctime = datetime.datetime.strftime(ctime_s, "%Y-%m-%d %H:%M:%S")
s = json.dumps(s)
s_new = re.sub(r'(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2})', ctime, s)
print(s_new)
结果:
替换字符串中的日期
ctime_s = datetime.datetime.now()
ctime = datetime.datetime.strftime(ctime_s, "%Y-%m-%d")
json_file = re.sub(r'(\d{4}-\d{1,2}-\d{1,2})', ctime, json_file.read())