Python的取模误区

标签 python datetime modulo

我有那个代码,我不认为我真的理解模如何返回余数,不擅长数学..

代码如下:

#import the datetime class
import datetime

#declare and initialize variables
strDeadline = ""
totalNbrDays = 0
nbrWeeks = 0
nbrDays = 0

#Get Today's date
currentDate = datetime.date.today()

#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")

deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()

#Calculate number of days between the two dates
totalNbrDays = deadline - currentDate

#For extra credit calculate results in weeks & days

nbrWeeks = totalNbrDays.days / 7

#The modulo will return the remainder of the division
#which will tell us how many days are left 
nbrDays = totalNbrDays.days%7

#display the result to the user

print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")

最佳答案

当您将一个整数除以另一个整数时,它并不总是均匀分布。例如,23/7 将为您提供 2 的余数,因为 23 = 7 * 3 + 2。 Modulo 为您提供除法运算的余数...23 % 7 = 2。当您的天数比一周的时间长时,这很有用。您可以使用整数除法(意味着商将是一个整数)来计算周数 23/7 = 3 然后取模来计算剩余的天数 23 % 7 = 2,告诉你 23 天等于 3 周零 2 天。

关于Python的取模误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673794/

相关文章:

python - 为什么使用 find_element(By...) 而不是 find_element_by_

python - Django 获取所有用户

python - 关于 python 日期时间类型

c++ - 如何在不使用堆栈或数组的情况下从 int 中提取每个数字? (C++)

python - 如何访问selenium中具有相同类名的第二个元素

python - Pandas 数据框 : group by year and month

javascript - iPad、iPhone Safari 浏览器 - 时间问题,时差 5 小时

Python 对 np 数组取模

php - 无法解释 php 取模结果

python - 通过子进程杀死 FFMPEG 命令