Python 中的一年中的某一天

pythonserver side programmingprogramming更新于 2025/11/4 3:56:17

假设我们有一个格式为"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"

输出

41

相关文章


有用资源