Python 中的年中天


假设我们有一个格式为“YYYY-MM-DD”的日期。我们必须返回该年的天数。因此,如果日期是“2019-02-10”,那么这是该年的第 41 天。

为了解决这个问题,我们将按照以下步骤进行操作 -

  • 假设 D 是一个天数数组,例如 [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  • 将日期转换为年、月和日的列表
  • 如果该年是闰年,则将日期 D[2] 设为 29
  • 将天数一直加到 mm – 1 月和之后的当天数。

示例

让我们看看以下实现以获得更好的理解 -

 现场演示

class Solution(object):
   def dayOfYear(self, date):
      days = [0,31,28,31,30,31,30,31,31,30,31,30,31]
      d = list(map(int,date.split("-")))
      if d[0] % 400 == 0:
         days[2]+=1
      elif d[0]%4 == 0 and d[0]%100!=0:
         days[2]+=1
      for i in range(1,len(days)):
         days[i]+=days[i-1]
      return days[d[1]-1]+d[2]
ob1 = Solution()
print(ob1.dayOfYear("2019-02-10"))

输入

"2019-02-10"

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

41

更新于: 2020 年 4 月 29 日

3K+ 浏览

开启你的事业

完成课程,获得认证

开始
广告