I have to return the day of the year (int) for a given string date (eg "September, 14, 2019" ) WITHOUT using datetime
. I also have to make it basic enough to where I can make two other similar functions for different calendars.
This is what I had before:
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)
But I just can't seem to convert it into this:
def day_of_year_to_date(self, day_of_year, year):
'''
Convert day of year to date.
'''
# ...
This should achieve the desired effect. I'm making a few assumptions since you didn't specify output format or input data.
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'
I'm making the simple assumption that each month is 30 days -- you're dictionary should be accurate to the month and year (and obviously doesn't require datetime to generate).
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}
First you will need some data structure to hold the number of days in each month like so:
month_data = [(1, “January”, 31), (2, “February”, 28), ... (12,”December”,31)]
Then you can do some modification for leap years :
if isLeapYear(year):
month_data[1][2] = 29
Then you can create a counter to track the month of the year :
month_of_year = 0
Then you can iterate over your month data subtracting the number of days in each month from your day_of_year
variable. The leftover amount will represent the day of the month :
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
Once you have the month of the year , and the day of the month it should be simple to return a string that represents the full date.
Of course you will have to do some error checking to make sure that the input is valid 0<day_of_year<365 or 366 if leap year. But I hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.