[英]How To Create A Procedure That Given Two Dates And Finds How Many Hours Between Them
So, as I mentioned in the title I should write a code like that.所以,正如我在标题中提到的,我应该编写这样的代码。 But I can't manage to understand how to do it.
但我无法理解如何做到这一点。 Here is my code:
这是我的代码:
# 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 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))
But that's not quite working for that question.但这并不完全适用于这个问题。 Am I following the wrong path?
我走错路了吗? Here is what I need to do:
这是我需要做的:
"You are asked to create a procedure that, given two dates, finds how many hours between these dates. This procedure should take 8 parameters as (day1, month1, year1, hour1, day2, month2, year2, hour2). "hour1" and "hour2" parameters must take integer values from 0 to 23. For example: “您被要求创建一个程序,给定两个日期,找出这些日期之间的小时数。该程序应采用 8 个参数,如(day1、month1、year1、hour1、day2、month2、year2、hour2)。“hour1”和“hour2”参数必须采用 integer 值从 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.".
Could anyone help me about it?有人可以帮我吗?
You're on the right way, your Date
-Object constructor should be named __init__
and not init
你走对了,你的
Date
-Object 构造函数应该命名为__init__
而不是init
class Date:
def __init__(self, d, m, y):
...
then your function already seems to return the corrent number of days, so you just need to add the hours into it.那么您的 function 似乎已经返回了正确的天数,因此您只需将小时数添加进去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.