I'm trying to parse xml file and convert all the unix timestamps in it to datetime...

<Sample>
<TimeStamp>1291052077</TimeStamp>
blah blah
blah blah
</Sample>

<Sample>
<TimeStamp>1291052077</TimeStamp>
blah blah
blah blah
</Sample>
</Content>

import fileinput

file = raw_input("Enter file: ")
file = open(file, "wb+") 

for line in fileinput.FileInput(file,inplace=1):
    if "TimeStamp" in line:
        line=line.replace(<old>,<new>)   // don't know how to get all instances of the time
        pass

print(datetime.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))

I've got some clues as above, but struggling to piece together things. Any thoughts?

Edited 6 Years Ago by blacknred: n/a

I would keep everything between the first ">" and "<" but if all of the records are the same, you could also replace "<TimeStamp>" and "</TimeStamp>" with nothing. Either way will get you to be able to
print(datetime.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))

Edited 6 Years Ago by woooee: n/a

Another easy way is formating as woooee just stated.

Here format so that your data show on line by line. So lets say you have the whole time stuff on line 5.

You just replace all line 5 with your new time stamp. Always think about future and updates. Planing is very important in programming.

Your case is solved. ;)

I have studied this very carefuly, that if a programe is well planed. Its very easy to update. No need for regex and crude methods. Regex in when all simple logic can not fix or you need need to find mixed up scatered data in a file.

Thats my take ;)

This article has been dead for over six months. Start a new discussion instead.