Created
April 30, 2015 18:27
-
-
Save hanksudo/e51f5372519f862f1358 to your computer and use it in GitHub Desktop.
(Python) Find next weekday or last weekday
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import timedelta | |
def next_weekday(date, weekday): | |
day_gap = weekday - date.weekday() | |
if day_gap <= 0: | |
day_gap += 7 | |
return date + timedelta(days=day_gap) | |
def last_weekday(date, weekday): | |
day_gap = weekday - date.weekday() | |
if day_gap >= 0: | |
day_gap -= 7 | |
return date + timedelta(days=day_gap) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
from datetime import datetime | |
from weekday import next_weekday, last_weekday | |
fmt = '%Y-%m-%d' | |
date = datetime(2015, 5, 1) | |
class WeekdayTestCase(unittest.TestCase): | |
def test_last_week_day(self): | |
self.assertEqual(last_weekday(date, 0).strftime(fmt), '2015-04-27') | |
self.assertEqual(last_weekday(date, 1).strftime(fmt), '2015-04-28') | |
self.assertEqual(last_weekday(date, 2).strftime(fmt), '2015-04-29') | |
self.assertEqual(last_weekday(date, 3).strftime(fmt), '2015-04-30') | |
self.assertEqual(last_weekday(date, 4).strftime(fmt), '2015-04-24') | |
self.assertEqual(last_weekday(date, 5).strftime(fmt), '2015-04-25') | |
self.assertEqual(last_weekday(date, 6).strftime(fmt), '2015-04-26') | |
def test_next_week_day(self): | |
self.assertEqual(next_weekday(date, 0).strftime(fmt), '2015-05-04') | |
self.assertEqual(next_weekday(date, 1).strftime(fmt), '2015-05-05') | |
self.assertEqual(next_weekday(date, 2).strftime(fmt), '2015-05-06') | |
self.assertEqual(next_weekday(date, 3).strftime(fmt), '2015-05-07') | |
self.assertEqual(next_weekday(date, 4).strftime(fmt), '2015-05-08') | |
self.assertEqual(next_weekday(date, 5).strftime(fmt), '2015-05-02') | |
self.assertEqual(next_weekday(date, 6).strftime(fmt), '2015-05-03') | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
last_weekday 这个函数不对,
当我使用weekday形参为0时,用2019年8月20号(星期二)的带入进去,算出上个星期是2019年8月19号(昨天),而正确答案是2019年8月12号(星期一),
而当我把weekday形参设为1时,计算出时间是2019年8月13号,所以当weekday为0时应该要算出2019年8月12号的
因此,last_weekday函数应该是: