使用python查找并调整XML中的日期和时间戳

2024-09-27 23:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图更改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}$

有人知道怎么做吗?在


Tags: 用户标记idtime格式时间xmlmanual
3条回答

使用此正则表达式查找所有日期:

\d{4}[-/]\d{2}[-/]\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z

filedata = filedata.split()
for line  in filedata:
    cur_date = re.findall('\d{4}[-/]\d{2[-/]\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z', line)
    print cur_date
    for match in cur_date
        line.replace(match,updateDate(match))

您只需要创建一个updateDate()函数来执行您想要的更新 在此函数中,您可以使用相同的正则表达式,但这次使用的是匹配的组,例如()。在

我认为把工作分成两部分比较容易

假设在本例中我们可以忽略时间戳嵌入到XML中,那么可以使用re.sub()来调整它们:

#!/usr/bin/env python2
import datetime as DT
import fileinput
import re

timestamp_regex = '(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z'

def add_two_days(m):
    numbers = map(int, m.groups())
    numbers[-1] *= 1000  # milliseconds -> microseconds
    try:
        utc_time = DT.datetime(*numbers)
    except ValueError:
        return m.group(0) # leave an invalid timestamp as is
    else:
        utc_time += DT.timedelta(days=2) # add 2 days
        return utc_time.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

replace_time = re.compile(timestamp_regex).sub
for line in fileinput.input('test.xml', backup='.bak', inplace=1, bufsize=-1):
    print replace_time(add_two_days, line),

为了简化时间戳的使用,它们被转换为datetime对象。您可以在这里使用timedelta()调整时间。在

fileinput.input(inplace=1)就地更改输入文件(在本例中,print将打印到该文件)。备份文件被复制到具有相同名称和附加的.bak文件扩展名的文件中。见How to search and replace text in a file using Python?

您可以使用这个:

(?P<YEAR>[\d]{4})-(?P<MONTH>([0][1-9])|([1][0-2]))-(?P<DAY>([0][1-9])|([12][0-9])|([3][01]))T(?P<HOUR>([01][0-9])|([2][0-3])):(?P<MINUTES>([0-5][0-9])):(?P<SECONDS>([0-5][0-9])).(?P<MILLIS>[0-9]{3})Z

然后您可以访问命名组,如下所示:

^{pr2}$

另外,你可以在这里看到现场演示:https://regex101.com/r/mA1rY4/1

相关问题 更多 >

    热门问题