Find and adjust the date and time stamp in XML using Python

advertisements

I'm trying to change all date values in an XML and subsequently add or subtract an user specified amount of time from the time stamps.

The timestamps are all of the format 2016-06-29T17:03:39.000Z However, they are not all enclosed in the same tags

My XML looks something like this:

<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>

I want to run through the XML file row by row, and search for the date/time string, then first find and replace the date, secondly add/subtract some amount of time from the timestamp.

This is my code so far:

import re
import xml.etree.ElementTree as et

name_file = 'test.txt'
fh = open(name_file, "r")
filedata = fh.read()
fh.close()

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

Does anyone have an idea on how to do this?


You can use this:

(?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

And then you can access the named groups like this:

cur_date.group('YEAR')

P.S. You can see live demo here: https://regex101.com/r/mA1rY4/1