Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ending 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!

like image 726
kovshenin Avatar asked Feb 10 '26 22:02

kovshenin


1 Answers

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.

like image 107
Brent Newey Avatar answered Feb 13 '26 12:02

Brent Newey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!