开发者

Need some Python datetime magic

Hey all. I don't think this should be very complicated but I just can't get it. I have a list of datetime objects starting at a certain date and en开发者_开发百科ding at one. Some days can be skipped. I can print them out like this:

for entry in dates:
    print entry

Which gives me the following output:

2010-11-29 10:00:00.0
2010-12-30 10:00:00.0 
2010-12-01 10:00:00.0 # Note that December 3rd has been skipped
...
2010-12-07 10:00:00.0

What I'd like to do is get an output like this:

Day 1: ok
Day 2: ok
Day 3: skipped
Day 4: ok
...
Day 10: ok

Could anybody help me out with some common sense here?

Thanks!


Here is a way to do this by converting your datetimes to dates. Rather than try to iterate over the dates themselves, we take a timedelta of the last date and the first date (this requires your dates to be sorted, I added a sorted call in case they aren't). Then we see if the first date plus the number of days is in your original set for each day in the range:

from datetime import datetime, timedelta
dts = [datetime(2010, 11, 29, 10, 0, 0), datetime(2010, 11, 30, 10, 0, 0),
       datetime(2010, 12, 4, 10, 0, 0)]
dates = sorted(d.date() for d in dts)

for d in range((dates[-1] - dates[0]).days + 1):
    st = 'ok' if dates[0] + timedelta(days=d) in dates else 'skipped'
    print 'Day %d: %s' % (d + 1, st)

Output:

Day 1: ok
Day 2: ok
Day 3: skipped
Day 4: skipped
Day 5: skipped
Day 6: ok

Note: I created my own example here because I'm not sure the example you used actually makes sense.


use the "rrule" module from the dateutil package, found at http://labix.org/python-dateutil

import datetime
from dateutil import rrule

dates = (datetime.datetime(2010, 11, 29),
         datetime.datetime(2010, 11, 30),
         datetime.datetime(2010, 12, 2))

all_dates = list(rrule.rrule(rrule.DAILY, count=5, 
                 dtstart=datetime.datetime(2010, 11,29)))

for (i, date) in enumerate(all_dates):
    if date in dates:
        status = "ok"
    else:
        status = "skipped"

    print "Day %s: %s" % (i+1, status)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜