【问题标题】:Convert date to day of year without using datetime在不使用日期时间的情况下将日期转换为一年中的某一天
【发布时间】:2021-02-28 05:54:27
【问题描述】:

我必须在不使用datetime 的情况下返回给定字符串日期(例如“2019 年 9 月 14 日”)的年份 (int)。我还必须使它足够基本,以便我可以为不同的日历制作另外两个类似的功能。


这是我之前的:

def date_to_day_of_year(self, month, day, year):
  '''
  Given the month, day and year of a date,
  return the number of the day in the year.
  '''
  day_of_year = 0
  for month_name, days_in_month in month_days.items():
      if month_name == month:
          break
      day_of_year += days_in_month
  day_of_year += day
  if self.is_leap_year(year) and ((month != 'Feb') and (month != 'Jan')):
      day_of_year += 1
  return day_of_year(month, day, year)

但我似乎无法将其转换为:

def day_of_year_to_date(self, day_of_year, year):
  '''
  Convert day of year to date.
  '''
  # ...

【问题讨论】:

    标签: python date date-arithmetic days


    【解决方案1】:

    这应该可以达到预期的效果。由于您没有指定输出格式或输入数据,因此我做了一些假设。

    def day_of_year_to_date(day_of_year, year):
        sum_of_days = 0
        for month_name, days_in_month in month_days.items():
            sum_of_days += days_in_month
            if sum_of_days > day_of_year:
                month = month_name
                day = str(days_in_month - sum_of_days%day_of_year)
                break
            else:
                pass
        return month+', '+day+' '+str(year)
    
    day_of_year = 110
    year = 2020
    day_of_year_to_date(day_of_year, year)
    
    #'April, 10 2020'
    

    我做了一个简单的假设,即每个月是 30 天——你的字典应该准确到月份和年份(显然不需要生成日期时间)。

    import datetime 
    month_days = {}
    for i in range(1,13):
        month_days[datetime.date(2008, i, 1).strftime('%B')] = 30
        
    month_days
    
    ###
    {'January': 30,
     'February': 30,
     'March': 30,
     'April': 30,
     'May': 30,
     'June': 30,
     'July': 30,
     'August': 30,
     'September': 30,
     'October': 30,
     'November': 30,
     'December': 30}
    

    【讨论】:

      【解决方案2】:

      首先,您需要一些数据结构来保存每个月的天数,如下所示:

      month_data = [(1, “January”, 31), (2, “February”, 28), ... (12,”December”,31)]
      

      然后你可以做一些闰年的修改:

      if isLeapYear(year):
          month_data[1][2] = 29
      

      然后您可以创建一个计数器来跟踪一年中的月份:

      month_of_year = 0
      

      然后您可以迭代您的月份数据,从您的 day_of_year 变量中减去每个月的天数。剩余金额将代表一个月中的哪一天:

      for month in month_data:
          if month[2] < day_of_year:
              day_of_year -= month[2]
              month_of_year ++
      day_of_month = day_of_year
      

      一旦您有了一年中的月份和一个月中的哪一天,返回一个代表完整日期的字符串应该很简单。

      当然,您必须进行一些错误检查以确保输入有效 0

      【讨论】:

        猜你喜欢
        • 2021-02-06
        • 2014-08-03
        • 2021-03-07
        • 2016-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-18
        相关资源
        最近更新 更多