Python:提供给定日期的开始和结束周数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19216334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: give start and end of week data from a given date
提问by shadowtdt09
day = "13/Oct/2013"
print("Parsing :",day)
day, mon, yr= day.split("/")
sday = yr+" "+day+" "+mon
myday = time.strptime(sday, '%Y %d %b')
Sstart = yr+" "+time.strftime("%U",myday )+" 0"
Send = yr+" "+time.strftime("%U",myday )+" 6"
startweek = time.strptime(Sstart, '%Y %U %w')
endweek = time.strptime(Send, '%Y %U %w')
print("Start of week:",time.strftime("%a, %d %b %Y",startweek))
print("End of week:",time.strftime("%a, %d %b %Y",endweek))
print("Data entered:",time.strftime("%a, %d %b %Y",myday))
out:
Parsing : 13/Oct/2013
Start of week: Sun, 13 Oct 2013
End of week: Sat, 19 Oct 2013
Sun, 13 Oct 2013
Learned python in the past 2 days and was wondering if there is a cleaner way to do this.This method works...it just looks ugly and It seems silly to have to create a new time variable for each date, and that there should be a way to offset the given date to the start and end of the week through a simple call but i have been unable to find anything on the internet or documentation that looks like it would work.
过去 2 天学习了 python,想知道是否有更简洁的方法来做到这一点。这种方法有效……它看起来很丑,而且必须为每个日期创建一个新的时间变量似乎很愚蠢,而且应该有是一种通过简单的电话将给定日期偏移到一周开始和结束的方法,但我一直无法在互联网或文档上找到任何看起来可行的内容。
回答by Hyperboreus
Use the datetime
module.
使用datetime
模块。
This will yield start and end of week (from Monday to Sunday):
这将产生一周的开始和结束(从周一到周日):
from datetime import datetime, timedelta
day = '12/Oct/2013'
dt = datetime.strptime(day, '%d/%b/%Y')
start = dt - timedelta(days=dt.weekday())
end = start + timedelta(days=6)
print(start)
print(end)
EDIT:
编辑:
print(start.strftime('%d/%b/%Y'))
print(end.strftime('%d/%b/%Y'))
回答by palamunder
Slight variation if you want to keep the standard time formatting and refer to the current day:
如果您想保持标准时间格式并参考当天,则略有不同:
from datetime import datetime, timedelta
today = datetime.now().date()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=6)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))