Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of datetimes except weekends Python

I'm trying to create a sequence of datetime object but excluding weekends. So far I've successfully created a sequence of dates from any given start date to end date, but I'm having trouble figuring out how to exclude weekends:

# Generate sequence of dates
startDate = datetime.datetime.strptime(start, '%Y-%m-%d').date()
endDate = datetime.datetime.strptime(end, '%Y-%m-%d').date()
nb_days = (endDate - startDate).days + 1  # + 1 because range is exclusive
dates = [startDate + datetime.timedelta(days=x) for x in range(nb_days)]
like image 516
Apollo Avatar asked Jun 18 '26 06:06

Apollo


1 Answers

The isoweekday() function returns the day of the week, with 1 a Monday.

[d for d in dates if not d.isoweekday() in [6,7]]
like image 100
chrisaycock Avatar answered Jun 19 '26 19:06

chrisaycock



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!