计算工作日,月和日的年份

时间:2016-04-15 19:44:09

标签: python date datetime

我有一堆没有年份的日期,格式如下:

Thu Apr 10
Mon Mar 28

在python中有一个简单的方法来确定这些日期的来源吗?

2 个答案:

答案 0 :(得分:1)

当然会出现一年以上有效的情况,但假设你想在晚些时候服用,如果有这种情况,那么这个算法应该可以正常工作。

For each string
    Take the Month(Apr) and the Date(10) 
    For each year from this year down to whenever you'd like to stop
        Make a datetime object with the Month, Date, and Year
        If the datetime object's .weekday is the same as the Day you have (Thu)
            You've found the right year

或者在python中,它可能看起来像这样:

import datetime

with open("yourFile") as f:
for line in f:  

    day = #get the day from the line  (0-30)
    month = #get the number representing the month from the line (0-11)

    year = 2016
    while True:
        testDate = datetime.date(year, month, day)
        weekday = #turn the string "Thu" or "Mon" into the number value 
                  #it represents (0-6)
        if testDate.weekday == weekday:
            #You have found a matching year!!!
        else:
            year = year + 1

答案 1 :(得分:0)

以下代码应该有效,您必须选择一年开始,然后选择step-1为时间,1为前进及时)它会给你第一年它遇到的条件为真:

import datetime
weekdays = {'Mon': 0, 'Tue': 1, 'Wed': 2, 'Thu': 3, 'Fri': 4, 'Sat': 5, 'Sun': 6}
months = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
          'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
dates = ['Thu Apr 10', 'Mon Mar 28']
startYear = 2016
step = -1
years = []

for date in dates:
  [weekDay, month, day] = date.split(' ')
  day = int(day)
  year = startYear
  while True:
    if datetime.date(year, months[month], day).weekday() == weekdays[weekDay]:
      years.append(year)
      break;
    else:
      year = year + step