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

Monday, April 27, 2009

Python readline example for newbie

Input files:

$ cat file1
Mr A
Mr B
Mrs C
Mr D
Mr E

$ cat file2
890
123
213
123


Output required:
Construct record sets with first line from file1 and next line from file2. i.e. the output should look something like this:

Record 1
Mr A
890

Record 2
Mr B
123

Record 3
Mrs C
213

Record 4
Mr D
123

Record 5
Mr E
--


The python script:

c=1
file1 = open('file1', 'r')
file2 = open('file2', 'r')

for lineA in file1:
print "Record "+str(c)
print lineA,
lineB=file2.readline()
if lineB == '':
print "--"
else:
print lineB
c = c + 1


Related functions and modules:

1) f.readline(): It reads a single line from the file and a newline character (\n) is left at the end of the string.
If f.readline() returns an empty string, it means the end of the file has been reached.
For a blank line it returns '\n', a string containing only a single newline. read more here (section 7.2.1)

2) str function: An example.

>>> c=2
>>> print "value is "+c
Traceback (most recent call last):
File "", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "value is "+str(c)
value is 2