所以,正如我在標題中提到的,我應該撰寫這樣的代碼。但我無法理解如何做到這一點。這是我的代碼:
# Python3 program two find number of
# days between two given dates
# A date has day 'd', month
# 'm' and year 'y'
class Date:
def init(self, d, m, y):
self.d = d
self.m = m
self.y = y
# To store number of days in
# all months from January to Dec.
monthDays = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
# This function counts the number of
# leap years before the given date
def countLeapYears(d):
years = d.y
# Check if the current year needs
# to be considered for the count
# of leap years or not
if (d.m <= 2):
years -= 1
# An year is a leap year if it is a
# multiple of 4, multiple of 400 and
# not a multiple of 100.
ans = int(years / 4)
ans -= int(years / 100)
ans = int(years / 400)
return ans
# This function returns number of
# days between two given dates
def getDifference(dt1, dt2):
# COUNT TOTAL NUMBER OF DAYS
# BEFORE FIRST DATE 'dt1'
# initialize count using years and day
n1 = dt1.y * 365 dt1.d
# Add days for months in given date
for i in range(0, dt1.m - 1):
n1 = monthDays[i]
# Since every leap year is of 366 days,
# Add a day for every leap year
n1 = countLeapYears(dt1)
# SIMILARLY, COUNT TOTAL NUMBER
# OF DAYS BEFORE 'dt2'
n2 = dt2.y * 365 dt2.d
for i in range(0, dt2.m - 1):
n2 = monthDays[i]
n2 = countLeapYears(dt2)
# return difference between
# two counts
return (n2 - n1)
# Driver Code
dt1 = Date(1, 9, 2014)
dt2 = Date(3, 9, 2020)
# Function call
print("Difference between two dates is",
getDifference(dt1, dt2))
但這對這個問題不太適用。我走錯路了嗎?這是我需要做的:
“你被要求創建一個程序,在給定兩個日期的情況下,找出這些日期之間的小時數。這個程序應該采用 8 個引數作為 (day1, month1, year1, hour1, day2, month2, year2, hour2)。“hour1”和“hour2”引數必須采用從 0 到 23 的整數值。例如:
- Given (1, 12, 2021, 0, 4, 12, 2021, 23) it should output "There are 95 hours.".
- Given (1, 12, 1990, 0, 1, 12, 2021, 18) it should output "There are 271770 hours.".
有人可以幫我嗎?
我無法為時間計算撰寫代碼。我不能使用日期時間
uj5u.com熱心網友回復:
你走對了,你的Date-Object 建構式應該被命名__init__而不是init
class Date:
def __init__(self, d, m, y):
...
那么您的函式似乎已經回傳了正確的天數,因此您只需要將小時數添加到其中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393766.html
上一篇:如何轉換長日期格式
