【发布时间】:2016-04-15 19:44:08
【问题描述】:
我有一堆没有年份的日期,格式如下:
Thu Apr 10
Mon Mar 28
在 python 中有没有一种简单的方法来识别这些日期的年份?
【问题讨论】:
-
不,因为这些日期可能匹配许多不同的年份,例如3 月 28 日是每隔几年的一个星期一。
我有一堆没有年份的日期,格式如下:
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
【讨论】: