简体   繁体   English

从工作日、月份和日期计算年份

[英]Calculate year from weekday, month, and day

I have a bunch of dates without years in the following format:我有一堆没有年份的日期,格式如下:

Thu Apr 10
Mon Mar 28

Is there a simple way in python to identify the year these dates come from? python中是否有一种简单的方法来识别这些日期来自的年份?

Of course there will be cases where more than one year is valid, but assuming that you would like to take the later year, if there is such a case, then this algorithm should work fine.当然会有超过一年有效的情况,但假设你想拿后一年,如果有这种情况,那么这个算法应该可以正常工作。

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

Or in python, it may look something like this:或者在 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

The code below should work, you'll have to pick a year to start from and a direction to go to as step ( -1 for back in time, 1 for forward in time) and it'll give you the first year it encounters for which the condition is true:下面的代码应该可以工作,你必须选择一年开始和一个方向作为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM