计算最后一个周五的日期
一、 解决问题
查找星期中某一天最后出现的日期,比如星期五
二、解决方案
datetime模块
三、代码说明
#!/usr/bin/env python
from datetime import timedelta
a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
c = a + b
print (c) #->2 days, 10:30:00
print (c.days) #->2
print (c.seconds) #->37800
print (c.seconds / 3600) #->10.5
print (c.total_seconds()/ 3600) #->58.5
from datetime import datetime
a = datetime(2017, 1, 17)
#加多少天
print (a + timedelta(days=22))
#减多少天
print (a + timedelta(days=-22))
now = datetime.today()
print (now)
print(now + timedelta(minutes=10))
# datetime 会自动处理闰年
a = datetime(2012, 3, 1)
b = datetime(2012, 2, 28)
print (a - b)
"""
dateutil 模块
执行更加复杂的日期操作。
"""
from datetime import datetime, timedelta
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
def get_previous_byday(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
#星期一索引为0
day_num = start_date.weekday()
day_num_target = weekdays.index(dayname)
days_ago = (7 + day_num - day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days=days_ago)
return target_date
print (get_previous_byday('Monday'))
四、关联知识
五、总结
六、代码地址
github地址:https://github.com/weichen666/python_cookbook
目录/文件:eight_selection/learn_data_date_time_datetime.py