calculate difference between two timestamps [newbie]

nukeymusic nukeymusic at gmail.com
Sun Dec 18 05:37:57 EST 2011


On 17 dec, 12:20, "Günther Dietrich" <gd.use... at spamfence.net> wrote:
> nukeymusic <nukeymu... at gmail.com> wrote:
> >I'm trying to calculate the difference in seconds between two
>
> [...]
>
> >>> import datetime
> >>> date1 = datetime.datetime.strptime("Dec-13-09:47:12", "%b-%d-%H:%M:%S")
> >>> date2 = datetime.datetime.strptime("Dec-13-09:47:39", "%b-%d-%H:%M:%S")
> >>> delta = date2 - date1
> >>> delta_seconds = (delta.days * 60 * 60 * 24) + delta.seconds + ((delta.microseconds + 500000) / 1000000)
>
> For very big time differences you should consider to use the Decimal
> arithmetics (standard module Decimal) instead of integer arithmetics
> for the last line.
> If you are sure, that you don't use fractional seconds, you can omit
> the part with 'delta.microseconds'.
>
> Best regards,
>
> Günther
That can very much Günther, this helped me a lot further, I'm only
struggling with one more problem to finish my first python-program.
Could you
tell me why I can't write to the outputfile as I do in the code
below:?
#!/usr/bin/python
#version 16/12/2011
#Example of testfile
#Dec-13-09:46:45 21.4 +4.76442190E-01 8.135530E-06 1.553691E+00
#Dec-13-09:47:12 21.4 +4.76439120E-01 8.135839E-06 1.553726E+00
#Dec-13-09:47:39 21.4 +4.76427260E-01 8.136261E-06 1.553853E+00
import datetime
f = open('testfile','r')
g = open('outputfile','w')
#get line 1 from input file:
line1=f.readline()
#get first element in line 1:
date1=line1.rsplit()[0]
#convert first element tot structured date time
struct_date1=datetime.datetime.strptime(date1, "%b-%d-%H:%M:%S")
for line in f:
 temp=line.rsplit()
 delta=datetime.datetime.strptime(temp[0], "%b-%d-%H:%M:%S")-
datetime.datetime.strptime(date1,  "%b-%d-%H:%M:%S")
 delta_seconds = (delta.days * 60 * 60 * 24) + delta.seconds +
((delta.microseconds + 500000) / 1000000)
 temp[0]=delta_seconds
#the following line is wrong, but I don't know how to fix it:
 g.write(temp)
#Close files
f.close()
g.close()

thanks in advance
nukey



More information about the Python-list mailing list