简体   繁体   中英

Arithmetic operations on dates in python

I want to know how many days is there between two dates in python, I'm using type "date" to store information. But if I just subtract two dates, I receive not an integer value, but some kind of tuple:

from datetime import *

a = date(2016, 9, 26)
b = date(2017, 1, 25)
delta = b - a

print('Interval is', delta, 'days long.')

Returns: Interval is 121 days, 0:00:00 days long.

But if I do it this way, I receive the number of days only.

from datetime import *

a = date(2016, 9, 26)
b = date(2017, 1, 25)

delta = b - a

print('Interval is', delta.days, 'days long.\n')

Returns: Interval is 121 long.

In Python documentation for version 3.6 object of class "date" has 3 arguments:

class datetime.date(year, month, day)

Why it still returns unnecessary time 0:00:00 delta when operating on dates itself?

Oh, now I get it! Subtraction does not return integer value with number of days, it returns object of type timedelta , and in this particular case you then have to explicitly access values by delta.days and delta.miliseconds .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM