calculate difference between two timestamps [newbie]

Vince vince at vince.ca
Sat Dec 17 06:19:09 EST 2011


On Sat, Dec 17, 2011 at 02:19:44AM -0800, nukeymusic wrote:
> I'm trying to calculate the difference in seconds between two
> timestamps, but I'm totally stuck:
> date1="Dec-13-09:47:12"
> date2="Dec-13-09:47:39"
> >>> diff=datetime.date(date2)-datetime.date(date1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: an integer is required
> 
> struct_date1=time.strptime(date1, "%b-%d-%H:%M:%S")
> struct_date2=time.strptime(date2, "%b-%d-%H:%M:%S")
> >>> diff=datetime.date(struct_date2)-datetime.date(struct_date1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: an integer is required

You're trying to compare two time.struct_time types when they need to be datetime.datetime types.

This will do the conversion for you:

import datetime,time

date1="Dec-13-09:47:12"
date2="Dec-13-09:47:39"

struct_date1=datetime.datetime(*time.strptime(date1, "%b-%d-%H:%M:%S")[:6])
struct_date2=datetime.datetime(*time.strptime(date2, "%b-%d-%H:%M:%S")[:6])

print struct_date2 - struct_date1



More information about the Python-list mailing list