Question

Here is the xml/kml file that I want to change: http://pastebin.com/HNwzLppa

The problem I am trying to solve: We have a kml file generated by data in a log file. The data sometimes has a time drift from GMT. (We are addressing this.) We have no control over the data that that process uses to generate the kml otherwise this whole exercise would be moot. We have written a script that checks to see the drift from GMT.

What I want to accomplish: Use the script we have alreaady written to input the hours, minutes and seconds differnce into this script. Find all the <timestamp> tags and extract the datetime and do a timedelta and write back the new timestamp, and then save the file.

What I have done so far:

import datetime
import time
import re
import csv
from bs4 import BeautifulSoup

#Open the KML file.
soup = BeautifulSoup(open('doc.kml'), "xml")

#Take keyboard input on hours minutes and seconds offset
hdata = raw_input("How many hours off is the file: ")
mdata = raw_input("How many minutes off is the file: ")
sdata = raw_input("How many seconds off is the file: ")

#Convert string to float for use in timedelta.
h = float(hdata)
m = float(mdata)
s = float(sdata)

#Find the timestamp tags in the file. In this case just the first 68.
times = soup('timestamp', limit=68)

#Loop thru the tags.
for time in times:  
timestring = time.text[8:27]
newdate = (datetime.datetime.strptime(timestring, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours= h, minutes = m, seconds = s))
times.replaceWith()

#Print to output the contents of the file.
print(soup.prettify())

The error I am getting:

Traceback (most recent call last):
File ".\timeshift.py", line 27, in <module>
times.replaceWith()
AttributeError: 'ResultSet' object has no attribute 'replaceWith'

My question is how do I do what I am trying to do and after the prettify statement write the file to disk.

Thanks in advance.

Was it helpful?

Solution

You are trying to replace the times result set (with s), not the single time tag (no s).

However, you probably don't want to replace the tag; you want to replace the text in the tag:

for time in times:  
    timestring = time.text[8:27]
    newdate = (datetime.datetime.strptime(timestring, "%Y-%m-%d %H:%M:%S") +
               datetime.timedelta(hours= h, minutes = m, seconds = s))
    newstring = soup.new_string(time.text[:8] + 
        newdate.strftime("%Y-%m-%d %H:%M:%S") + time.text[27:])
    time.string.replaceWith(newstring)

This creates a new NavigableString object with soup.new_string(), and replaces the original string child node on time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top