所有星期二和星期三都在一个日期范围内:是否有更多的pythonic方式?

时间:2015-12-20 15:47:15

标签: python datetime time

我希望在2015-11-02和2015-12-14之间找到所有星期二和星期三(datetime对象)。这有效:

from datetime import datetime, timedelta

l = []
for i in range(100):
   d = datetime(2015,11,2) + timedelta(days=i)
   if d > datetime(2015,12,14):
       break
   if d.weekday() == 1 or d.weekday() == 2:   # tuesday or wednesday
       l.append(d)
print l   
  

[datetime.datetime(2015,11,3,0,0),datetime.datetime(2015,11,4,0​​,0),datetime.datetime(2015,11,10,0,0),datetime .datetime(2015,11,11,0,0),datetime.datetime(2015,11,17,0,0),datetime.datetime(2015,11,18,0,0),datetime.datetime(2015, 11,24,0,0),datetime.datetime(2015,11,25,0,0),datetime.datetime(2015,12,1,0,0),datetime.datetime(2015,12,2,0) ,0),datetime.datetime(2015,12,8,0,0),datetime.datetime(2015,12,9,0,0)]

有更多的pythonic方法吗?

3 个答案:

答案 0 :(得分:3)

这是第三方模块python-dateutils

from dateutil.rrule import rrule, DAILY, TU, WE
import datetime as dt

results = rrule(DAILY,
        dtstart = dt.datetime(2015,11,2),
        until = dt.datetime(2015, 12, 14),
        byweekday = (TU, WE),
)


for result in results:
    print(result)

--output:--
2015-11-03 00:00:00
2015-11-04 00:00:00
2015-11-10 00:00:00
2015-11-11 00:00:00
2015-11-17 00:00:00
2015-11-18 00:00:00
2015-11-24 00:00:00
2015-11-25 00:00:00
2015-12-01 00:00:00
2015-12-02 00:00:00
2015-12-08 00:00:00
2015-12-09 00:00:00

答案 1 :(得分:2)

由于我已经使用ORA-01031: insufficient privileges ,因此可以使用:

var ref = cordova.InAppBrowser.open('http://apache.org', '_blank');
ref.addEventListener('loadstop', function() {
    ref.executeScript({file: "http://www.yourwebsite.com/myscript.js"});
});

答案 2 :(得分:0)

 date_range=pd.date_range(start="2015-11-02", end="2015-12-14",freq="D")
 date_range=[x for x in [x if x.dayofweek in [2,3] else None for x in date_range] if x]

 print(date_range)

输出

 [Timestamp('2015-11-04 00:00:00', freq='D'), 
  Timestamp('2015-11-05 00:00:00', freq='D'), 
  Timestamp('2015-11-11 00:00:00', freq='D'), 
  Timestamp('2015-11-12 00:00:00', freq='D'), 
  Timestamp('2015-11-18 00:00:00', freq='D'), 
  Timestamp('2015-11-19 00:00:00', freq='D'), 
  Timestamp('2015-11-25 00:00:00', freq='D'), 
  Timestamp('2015-11-26 00:00:00', freq='D'), 
  Timestamp('2015-12-02 00:00:00', freq='D'), 
  Timestamp('2015-12-03 00:00:00', freq='D'), 
  Timestamp('2015-12-09 00:00:00', freq='D'), 
  Timestamp('2015-12-10 00:00:00', freq='D')]