神不在的星期二
>>> from datetime import datetime, timedelta>>> d = datetime.strptime('2013-05-27', '%Y-%m-%d') # Monday>>> t = timedelta((12 - d.weekday()) % 7)>>> d + tdatetime.datetime(2013, 6, 1, 0, 0)>>> (d + t).strftime('%Y-%m-%d')'2013-06-01'我使用(12 - d.weekday()) % 7给定日期与下一个星期六之间的天数来计算增量,因为weekday介于0(星期一)至6(星期日)之间,所以星期六为5。但是:5和12是相同的模7(是的,我们一周有7天:-))所以12 - d.weekday()在6到125 - d.weekday()之间,在5到-1之间因此,这使我无法处理否定情况(星期日为-1)。这是任何工作日的非常简单的版本(无需检查):>>> def get_next_weekday(startdate, weekday): """ @startdate: given date, in format '2013-05-25' @weekday: week day as a integer, between 0 (Monday) to 6 (Sunday) """ d = datetime.strptime(startdate, '%Y-%m-%d') t = timedelta((7 + weekday - d.weekday()) % 7) return (d + t).strftime('%Y-%m-%d')>>> get_next_weekday('2013-05-27', 5) # 5 = Saturday'2013-06-01'
回首忆惘然
我发现这个摆非常有用。只需一行In [4]: pendulum.now().next(pendulum.SATURDAY).strftime('%Y-%m-%d')Out[4]: '2019-04-27'请参阅下面的更多细节:In [1]: import pendulumIn [2]: pendulum.now()Out[2]: DateTime(2019, 4, 24, 17, 28, 13, 776007, tzinfo=Timezone('America/Los_Angeles'))In [3]: pendulum.now().next(pendulum.SATURDAY)Out[3]: DateTime(2019, 4, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))In [4]: pendulum.now().next(pendulum.SATURDAY).strftime('%Y-%m-%d')Out[4]: '2019-04-27'