本文介绍了寻找下一个星期六的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用Python查找下一个星期六的日期?最好使用 datetime 并采用'2013-05-25'格式?
How would one go about finding the date of the next Saturday in Python? Preferably using datetime and in the format '2013-05-25'?
推荐答案>>> from datetime import datetime, timedelta >>> d = datetime.strptime('2013-05-27', '%Y-%m-%d') # Monday >>> t = timedelta((12 - d.weekday()) % 7) >>> d + t datetime.datetime(2013, 6, 1, 0, 0) >>> (d + t).strftime('%Y-%m-%d') '2013-06-01'
我使用(12-d.weekday())%7 来计算给定日期与下一个星期六之间的天数差异,因为 weekday 在0(星期一)之间和6(星期日),所以星期六是5.但是:
I use (12 - d.weekday()) % 7 to compute the delta in days between given day and next Saturday because weekday is between 0 (Monday) and 6 (Sunday), so Saturday is 5. But:
- 5和12是相同的7模(是的,我们一周有7天:-))
- 因此 12-d.weekday()在6到12之间,其中 5-d.weekday()介于5和-1
- 因此,这使我无法处理否定情况(星期日为-1).
- 5 and 12 are the same modulo 7 (yes, we have 7 days in a week :-) )
- so 12 - d.weekday() is between 6 and 12 where 5 - d.weekday() would be between 5 and -1
- so this allows me not to handle the negative case (-1 for Sunday).
这是任何工作日的非常简单的版本(无需检查):
Here is a very simple version (no check) for any weekday:
>>> 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'更多推荐
寻找下一个星期六的日期
发布评论