简体   繁体   中英

Differences between two dates in python

from datetime import date
import random    
earlier_date = date(2017, 6, random.randint(1, 25))    
later_date = date(2017, 6, random.randint(earlier_date.day + 1, 28))    
days_between = (later_date - earlier_date)    
print("There are",days_between,"days between", earlier_date, "and", later_date)

The output i have (full difference)

There are 18 days, 0:00:00 days between 2017-06-01 and 2017-06-19

The Output I want (day difference only)

There are 3 days between 2017-06-22 and 2017-06-25

Use days_between.days to the days difference. I've also add a s-check for day grammar

# String parts
print("There are", days_between.days, "day" + ('s' if days_between.days > 1 else '') +
      " between", earlier_date, "and", later_date)

# f-string
print(f"There are {days_between.days} day{'s' if days_between.days > 1 else ''} "
      f"between {earlier_date} and {later_date}")

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