python - 将日期转换为一年中的某一天,而不使用日期时间

标签 python date date-arithmetic days

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


这是我之前的:

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.
  '''
  # ...

最佳答案

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

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}

关于python - 将日期转换为一年中的某一天,而不使用日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64868090/

相关文章:

python - images.get_serving_url() 可以服务哪些类型的文件?

sql - Oracle to_date SQL 格式问题,

python - sklearn 绘制 SVM 分类器的结果

pandas - 为什么pandas max 函数没有返回正确的最大日期?

MySQL 查询具有最近日期的行

JavaScript 日期变量赋值

sql - 将时间戳四舍五入到最接近的半小时而不遗漏丢失的数据

cocoa - 计算当前时间和下一个事件之间的秒数

javascript - 典型的 AngularJS 工作流程和项目结构(使用 Python Flask)

python - pyqt4中带有子菜单的下拉菜单