0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで2つの日付の間の日数を求める

Last updated at Posted at 2022-10-09

西暦で考える場合は、0年12月31日からの経過日数をそれぞれ2つの日付に対して求め、差を求めれば、欲しい日数が求められます。

西暦、月、日の順に日付が若いほうから順番に入力されたときの実行例:

# うるう年かどうか判定する関数
def uruu(year):
    is_uruu = True
    if year % 100 == 0 and year % 400 > 0:
        is_uruu = False
    elif year % 4 > 0:
        is_uruu = False
    return is_uruu
# 入力
year1 = int(input())
month1 = int(input())
day1 = int(input())
year2 = int(input())
month2 = int(input())
day2 = int(input())

sum = 0
sum2 = 0
# monthday[i]がi月の日数を含むように定義する。ただし、2月は28日に設定し、うるう年の時はそのつど+1して考える
monthday = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 0年12月31日からの経過日数をそれぞれ求め、差を求める
# 一つ前の年までの日数をうるう年を考慮して数えて足す
for i in range(1,year1):
    if uruu(i):
        sum += 366
    else:
        sum += 365
# 一つ前の月までの日数をうるう年を考慮して数えて足す
for i in range(1,month1):
    if uruu(year1) and (i == 2):
        sum += monthday[i] + 1
    else:
        sum += monthday[i]
# 与えられた月の日付を足せばいい
sum += day1
for i in range(1,year2):
    if uruu(i):
        sum2 += 366
    else:
        sum2 += 365
for i in range(1,month2):
    if uruu(year2) and (i == 2):
        sum2 += monthday[i] + 1
    else:
        sum2 += monthday[i]
sum2 += day2
# 出力
print(sum2-sum)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?