lost and found ( for me ? )

Python : convert to localtime from epoch time

small tips.


# python --version
Python 2.7.3

1. convert space-demilited text file’s timestamp from epoch to localtime



# cat space-demilited-ephoc.txt
1342199723 hello bye

python script
# cat -n space-demilited-text-file-convert-to-localtime-from-epoch.py
    1 #!/usr/bin/env python
    2 # -*- coding: UTF-8 -*-
    3
    4 import sys
    5 import time
    6
    7 arg = sys.argv[1]
    8 f = open(arg, 'r')
    9
   10 for line in f:
   11        s = line.split()
   12        a = s[0]
   13        s[0] = time.ctime(float(a))
   14        print " ".join(s)
   15
   16 f.close()

convert to localtime from epoch time.
# ./space-demilited-text-file-convert-to-localtime-from-epoch.py space-demilited-ephoc.txt
Sat Jul 14 02:15:23 2012 hello bye

2. convert comma-demilited text file’s timestamp from epoch to localtime

# cat comma-demilited-ephoc.txt
1342199723,hello,bye

python script
# cat -n comma-demilited-text-file-convert-to-localtime-from-epoch.py
    1 #!/usr/bin/env python
    2 # -*- coding: UTF-8 -*-
    3
    4 import sys
    5 import time
    6 import csv
    7
    8 arg = sys.argv[1]
    9 f = open(arg, 'r')
   10 reader = csv.reader(f)
   11
   12 for line in reader:
   13        a = line[0]
   14        line[0] = time.ctime(float(a))
   15        print ",".join(line)
   16
   17 f.close()

convert to localtime from epoch
# ./comma-demilited-text-file-convert-to-localtime-from-epoch.py comma-demilited-ephoc.txt
Sat Jul 14 02:15:23 2012,hello,bye

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.