Friday, October 16, 2009

Python - time difference between dates


Required:

Find the time difference between two dates (of following format) in seconds and in hh:mm:ss format.

e.g.

date1='Oct/09/2009 10:58:01' and
date2='Oct/10/2009 12:17:10'

find the difference between date1 and date2 in seconds(i.e. 91149 seconds) and later convert it to hh:mm:ss format (i.e. 25:19:09).

The complete python program:

import sys,time,string,getopt

def usage():
print "Usage: adbtimediff.py -f <fromTime> -t <toTime> \n"
sys.exit(2)


def parse_args():
global fromTime,toTime
fromTime = toTime = ""

try:
opts, args = getopt.getopt(sys.argv[1:], "f:t:", ["fromtime", "totime"])
except getopt.GetoptError:
print "Invalid arguments, exiting"
sys.exit(2)

for arg, val in opts:
if arg in ("-f","--fromtime"):
fromTime = val
elif arg in ("-t","--totime"):
toTime = val

if fromTime == toTime == "" :
usage()

def compute_time(time1):
t = time1.split(':')
return time.mktime(time.strptime(":".join(t[0:len(t)]),"%b/%d/%Y %H:%M:%S"))

def subtract(list):
return list[1] - list[0]

def time_convert(secs):
secs = int(secs)
mins = secs // 60
hrs = mins // 60
return "%02d:%02d:%02d" % (hrs, mins % 60, secs % 60)

def main():
parse_args()
print "Fromtime : " + str(fromTime) + '\n' + "Totime : " + str(toTime)
timelist = [ fromTime, toTime ]
s = map(compute_time,timelist)
d = subtract(s)
print "diff in seconds : " + str(d)
f = str(d).split('.')
final = time_convert(f[0])
print "Total difference in required format : " + str(final)

main()


Executing the above script:

$ python timediff.py -f 'Oct/09/2009 10:58:01' -t 'Oct/10/2009 12:17:10'

Output:

Fromtime : Oct/09/2009 10:58:01
Totime : Oct/10/2009 12:17:10
diff in seconds : 91149.0
Total difference in required format : 25:19:09

Related concepts and posts:

- Convert seconds to hh:mm:ss format using python
- Python time.mktime
- Python time.strftime
- Python map
- Python getopt

Wednesday, October 14, 2009

Python - seconds to hh-mm-ss conversion

Solution1: Using python 'time' module strftime function.
 
Python 2.5.2 (r252:60911, Jul 22 2009, 15:35:03)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(7302))
'02:01:42'
>>> time.strftime('%H:%M:%S', time.gmtime(86399))
'23:59:59'
>>> time.strftime('%H:%M:%S', time.gmtime(86405))
'00:00:05'

So as seen above this solution works only for num seconds < 1 day (86400 seconds)

Solution2: Using python datetime module, timedelta object.

>>> import datetime
>>> x = datetime.timedelta(seconds=7302)
>>> str(x)
'2:01:42'
>>> x = datetime.timedelta(seconds=86399)
>>> str(x)
'23:59:59'
>>> x = datetime.timedelta(seconds=86405)
>>> str(x)
'1 day, 0:00:05'

Solution3: Using normal division in python

import sys

secs = int(sys.argv[1])
mins = secs // 60
hrs = mins // 60

#hh:mm:ss
print "%02d:%02d:%02d" % (hrs, mins % 60, secs % 60)

#mm:ss
print "%02d:%02d" % (mins, secs % 60)

Executing it:

$ python timeconv.py 7302
02:01:42
121:42

$ python timeconv.py 86399
23:59:59
1439:59

$ python timeconv.py 86405
24:00:05
1440:05

Tuesday, September 15, 2009

Find text string in file in Python

Each line of file "querymapping.txt" contains two fields.
1st field is a sql query and
2nd one is a filename where the output of that sql query is stored.

$ cat querymapping.txt
select * from tab_fan_details;|/tmp/query7
select * from tab_fan_speed_details;|/tmp/query4
select * from tab_fan_spec;|/tmp/query1

Required:

Write a python function to look-up a particular sql query (send as 1st argument to the script ) in the querymapping.txt file and return the query output filename. If no match found return default filename as '/tmp/query0'

The python program:

import sys
default='/tmp/query0'

def lookupfilename(query):
'''Lookup query output filename from query'''
for line in open('querymapping.txt'):
if query.strip() in line.strip().split("|")[0]:
return line.strip().split("|")[1]
return default

fname=lookupfilename(sys.argv[1])
print fname

Executing the script:

$ python qlookup.py "select * from tab_fan_speed_details;"
/tmp/query4

$ python qlookup.py "select * from tab_fan_speed_details_new;"
/tmp/query0

Related post:

- Lookup file in python using dictionary

Sunday, September 13, 2009

Print file content to output - Python

Required: Write a python program to print the content of a file to output (same as Linux/UNIX cat command do)

Way1: Using file.read file object in python

import sys,os.path

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
try:
f = open(sys.argv[1], 'r')
print f.read(),
f.close()
except IOError:
print "File" + sys.argv[1] + "does not exist."


Execute it this way: To print the contents of file.txt to the output.

$ python cat-read.py file.txt


Way2: Another similar python program using file.readline

import sys

def readfile(fname):
f = file(fname)
while True:
line = f.readline()
if len(line) == 0:
break
print line.strip() #Avoid strip: print line,
f.close()

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
readfile(sys.argv[1])


Read about python file()
In python 3.0 file() is removed.

Related concepts:

Thursday, August 27, 2009

Writing factorial function in Python - newbie

The recursive version:

import sys

Usage = """
Usage:
$ python factorial.py
"""

def fact(x):
if x == 0:
return 1
else:
return x * fact(x-1)

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
else:
print Usage

Executing:

$ python factorial.py 6
720

A shorter version of the above:

import sys

Usage = """
Usage:
$ python factorial.py
"""

def fact(x):
return (1 if x==0 else x * fact(x-1))

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
else:
print Usage

Or a non-recursive version

def fact(x):
f = 1
while (x > 0):
f = f * x
x = x - 1
return f

And in python 2.6, Math module (Mathematical functions) provides factorial function (math.factorial(x))

$ /jks/bin/python2.6
Python 2.6.2 (r262:71600, Jun 17 2009, 22:31:41)
[GCC 3.3.3 (Debian 20040306)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.factorial(6)
720
>>>


Related concepts:
- Python math module