Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不使用datetime将日期转换为一年中的某一天_Python_Date_Date Arithmetic_Days - Fatal编程技术网

Python 不使用datetime将日期转换为一年中的某一天

Python 不使用datetime将日期转换为一年中的某一天,python,date,date-arithmetic,days,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

我必须返回给定字符串日期(例如“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年中之日至日期(年中之日,年):
天数之和=0
对于月\名,月\中的天\月\天。项()
天数总和+=月内天数
如果天数之和>年份之日:
月份=月份名称
day=str(月内天数-年内天数百分比的总和)
打破
其他:
通过
返回月份+'、'+天+'+月份(年)
年中的日=110
年份=2020年
年月日至年月日(年月日)
#'2020年4月10日'
我做了一个简单的假设,每个月是30天——你的字典应该精确到月份和年份(显然不需要datetime来生成)

导入日期时间
月日={}
对于范围(1,13)内的i:
月日[datetime.date(2008,i,1).strftime('%B')]=30
月日
###
{'1月30日},
二月三十号,,
三月三十号,,
四月三十号,,
五月三十日,
六月三十号,,
七月三十号,,
八月三十号,,
九月三十号,,
10月30日,
11月30日,
十二月三十日

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

month_data = [(1, “January”, 31), (2, “February”, 28), ... (12,”December”,31)]
然后,您可以对闰年进行一些修改:

if isLeapYear(year):
    month_data[1][2] = 29
month_of_year = 0
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
然后,您可以创建一个计数器来跟踪一年中的月份:

if isLeapYear(year):
    month_data[1][2] = 29
month_of_year = 0
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
然后,您可以迭代月数据,从
day\u of_year
变量中减去每个月的天数。剩余金额将代表该月的

if isLeapYear(year):
    month_data[1][2] = 29
month_of_year = 0
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
月中月数据:
如果月[2]<年中的日:
年中之日-=月[2]
年月++
月日=年日
一旦有了一年中的月份和月份中的日期,就可以简单地返回一个表示完整日期的字符串

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