【问题标题】:Calculate year from weekday, month, and day根据工作日、月份和日期计算年份
【发布时间】:2016-04-15 19:44:08
【问题描述】:

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

Thu Apr 10
Mon Mar 28

在 python 中有没有一种简单的方法来识别这些日期的年份?

【问题讨论】:

  • 不,因为这些日期可能匹配许多不同的年份,例如3 月 28 日是每隔几年的一个星期一。

标签: python date datetime


【解决方案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

【讨论】:

  • @MattDMo 当您发表评论时,我还没有完成 Python 代码的输入。你现在可以看到python代码了。但无论如何,伪代码会很有帮助。为什么你认为它没用?
  • @MatthewCliatt 谢谢。我希望有一个内置的数据时间功能可以做到这一点,但是我将使用你的蛮力方法。
  • 你的皮肤一定很薄。您确实知道,不是吗,连续投票每晚都会被捕获并反转?对被否决的帖子发表愚蠢的评论也无助于隐藏您的身份。我建议你在坏事发生之前把它关掉。我对你的帖子投了反对票,因为你试图成为 FGITW,但你甚至没有做出一点积极的贡献——只是一些漫无边际的甚至是伪代码,对任何人都没有帮助,尤其是一个在 Python 中寻求帮助的 OP。可以先给代码,再展开,if代码解决问题。你的没有。
  • 请记住,帖子是在看到帖子的那一刻被判断的——我们完全不知道您是否打算回来清理。
  • @MattDMo 我仍然不认为您的反对和评论是必要的。我看到您的否决票的有效性,但是在我看来,您的评论是不可原谅的。我已经看到在许多情况下可以接受伪代码作为答案。我认为这是其中一种情况。如果你没有,那么你应该这么说。仅仅说您不喜欢某个答案对问题发布者、回答者或未来的读者没有帮助。如果您认为我的回答不好,为什么不说为什么?它只能帮助我和其他人看到另一种观点得到解释。
【解决方案2】:

下面的代码应该可以工作,你必须选择一个开始的年份和一个去往的方向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

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多