簡體   English   中英

從工作日、月份和日期計算年份

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

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

Thu Apr 10
Mon Mar 28

python中是否有一種簡單的方法來識別這些日期來自的年份?

當然會有超過一年有效的情況,但假設你想拿后一年,如果有這種情況,那么這個算法應該可以正常工作。

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

下面的代碼應該可以工作,你必須選擇一年開始和一個方向作為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