我试图更改XML中的所有日期值,然后从时间戳中添加或减去用户指定的时间量。在
时间戳的格式均为2016-06-29T17:03:39.000Z 但是,它们并不都包含在同一个标记中
我的XML如下所示:
<Id>2016-06-29T17:03:37.000Z</Id>
<Lap StartTime="2016-06-29T17:03:37.000Z">
<TotalTimeSeconds>6906</TotalTimeSeconds>
<DistanceMeters>60870.5</DistanceMeters>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2016-06-29T17:03:37.000Z</Time>
我想逐行遍历XML文件,搜索日期/时间字符串,然后首先查找并替换日期,然后从时间戳中添加/减去一些时间。在
这是我目前为止的代码:
^{pr2}$有人知道怎么做吗?在
使用此正则表达式查找所有日期:
您只需要创建一个updateDate()函数来执行您想要的更新 在此函数中,您可以使用相同的正则表达式,但这次使用的是匹配的组,例如()。在
我认为把工作分成两部分比较容易
假设在本例中我们可以忽略时间戳嵌入到XML中,那么可以使用
re.sub()
来调整它们:为了简化时间戳的使用,它们被转换为
datetime
对象。您可以在这里使用timedelta()
调整时间。在fileinput.input(inplace=1)
就地更改输入文件(在本例中,print
将打印到该文件)。备份文件被复制到具有相同名称和附加的.bak
文件扩展名的文件中。见How to search and replace text in a file using Python?您可以使用这个:
然后您可以访问命名组,如下所示:
^{pr2}$另外,你可以在这里看到现场演示:https://regex101.com/r/mA1rY4/1
相关问题 更多 >
编程相关推荐