因此,要计算出自 10 月 15 日以来的任何日期是星期几,您可以使用一个简单的算术运算,我的问题是我已从文件中读取了日期(例如 2009-06-12)并且我将等式代入:
w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7
日期的格式为 yyyy-mm-dd,我的代码如下所示:
count = 5
f = open('/Users/student/Desktop/Harry.txt').readlines()[count]
Y = f[2:4]
C = f[:2]
m = f[5:7]
d = f[8:10]
w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7
if w == 0:
print (f, "is a Sunday")
elif w == 1:
print (f, "is a Monday")
elif w == 2:
print (f, "is a Tuesday")
elif w == 3:
print (f, "is a Wednesday")
elif w == 4:
print (f, "is a Thursday")
elif w == 5:
print (f, "is a Friday")
elif w == 6:
print (f, "is a Saturday")
澄清一下:
w = day of the week counting from Sunday = 0 Monday = 1
d = the day of the month (for e.g. 28th 13th)
m = month number where March = 1 etc.
Y = last 2 digits of year
C = first 2 digits of year
但是我收到这个错误
Traceback (most recent call last):
File "/Users/student/Documents/workspace/Tutorial Challenges/src/Day_Of_The_Week.py", line 7, in <module>
w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7
TypeError: can't multiply sequence by non-int of type 'float'
非常感谢您的帮助。
最佳答案
Y
、C
、m
和 d
都是字符串。您想先将它们转换为整数:
Y = int(f[2:4])
C = int(f[:2])
...
不过,你确定这个方程有效吗?看起来它会产生很多非整数工作日。你可能抄错了。另外,方括号不是 Python 中的分组运算符;而是一个分组运算符。它们是列表构造语法。您需要将这些方括号替换为 w
表达式中的圆括号。 (或者这些括号应该是下限运算符吗?如果是这样,您需要来自 math
模块的 math.floor
,或者只是 int
如果截断没问题。)
关于python - 在 Python 3.3 中解方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646931/