Saturday, April 25, 2009

Apply operation on a field - python


Input file:

$ cat test.txt
2|Z|1219071600|AF|0
3|N|1219158000|AF|89
4|N|1220799600|AS|12
1|Z|1220886000|AS|67
5|N|1220972400|EU|23
6|R|1221058800|OC|89


Required:
The operation is simple; we need to print the above file after converting the 3rd field(UNIX epoch time) to human readable date format.
Python time module provides a function called ctime using which we can convert UNIX epoch time to human readable string date format(local time of the box)

The script:

import time

fp = open("test.txt", "rU")
lines = fp.readlines()
fp.close()

for line in lines:
f=line.split("|")
t="|".join(f[0:2])+"|"+time.ctime(int(f[2]))+"|"+"|".join(f[3:])
print t.rstrip()

Executing the above script:

$ python epoch-convert.py
2|Z|Mon Aug 18 15:00:00 2008|AF|0
3|N|Tue Aug 19 15:00:00 2008|AF|89
4|N|Sun Sep 7 15:00:00 2008|AS|12
1|Z|Mon Sep 8 15:00:00 2008|AS|67
5|N|Tue Sep 9 15:00:00 2008|EU|23
6|R|Wed Sep 10 15:00:00 2008|OC|89


Related module:
- Python time module read here

0 Comments: