# Re: How to find out a date/time difference

Discussion in 'Python' started by Nico Grubert, May 24, 2006.

1. ### Nico GrubertGuest

> I use datetime class in my program and now
> I have two fields that have the datetime format like this
> datetime.datetime(2006, 5, 24, 16, 1, 26)

> How can I find out the date/time difference ( in days) of such two
> fields?

you could do this:

>>> a = datetime.datetime(2006, 5, 24, 16, 1, 26)
>>> b = datetime.datetime(2006, 5, 20, 12, 1, 26)
>>> a-b

datetime.timedelta(4)
# 4 days

>>> b = datetime.datetime(2006, 5, 20, 12, 1, 26)
>>> x = a-b
>>> x

datetime.timedelta(4, 14400)
>>> str(x)

'4 days, 4:00:00'

Regards,
Nico

Nico Grubert, May 24, 2006

2. ### Guest

And if you want the number of days:

py> d = datetime.datetime(2006,5,24,16,34) -
datetime.datetime(2006,5,23,12,1)
py> d.days
1
py> d = datetime.datetime(2006,5,24,16,34) -
datetime.datetime(2006,5,23,19,1)
py> d.days
0

, May 24, 2006

3. ### Klaus Alexander SeistrupGuest

Nico Grubert skrev:

> you could do this:
>
> >>> a = datetime.datetime(2006, 5, 24, 16, 1, 26)
> >>> b = datetime.datetime(2006, 5, 20, 12, 1, 26)
> >>> a-b

> datetime.timedelta(4)
> # 4 days

Or

#v+

>>> print (a-b).days

4
>>>

#v-

Mvh,

--
Klaus Alexander Seistrup
SubZeroNet, Copenhagen, Denmark
http://magnetic-ink.dk/

Klaus Alexander Seistrup, May 24, 2006