我必须返回给定字符串日期(例如“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/