如何在python中计算两天之间的天数?

时间:2019-05-17 10:25:38

标签: python

我正在尝试计算给定两天的黑白天数,我面临的问题是第一天比第二天晚。 示例-如果第一天是星期六,第二天是星期一,那么存在的天数应该是3天,但是我的代码无法执行此操作。

a="saturday monday 1 2"
f=a.split(" ")
l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
g=abs(l.index(f[0])-l.index(f[1]))+1
print(g)

2 个答案:

答案 0 :(得分:1)

减去这两天的索引,并取7作为模。将其放入函数中,我们就有

def day_diff(a, b):
    l = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

    return (l.index(b) - l.index(a))%7

print(day_diff('saturday', 'monday'))
#2
print(day_diff('monday', 'saturday'))
#5
print(day_diff('monday', 'monday'))
#0
print(day_diff('monday', 'sunday'))
#6

答案 1 :(得分:1)

这将解决您的问题:

a="saturday monday 1 2"
#a= "monday tuesday"
f=a.split(" ")
l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
sym = (l.index(f[0])-l.index(f[1]))
if sym <= 0:
    g=abs(sym)+1
else:
    new_sym = 7 - sym
    g=abs(new_sym)+1