Python:从给定日期开始和结束一周的数据 [英] Python: give start and end of week data from a given date

查看:329
本文介绍了Python:从给定日期开始和结束一周的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

过去2天学习了python,想知道是否有更清洁的方法来执行此方法。此方法看起来很丑,不得不创建一个新的方法似乎很愚蠢每个日期的时间变量,并且应该有一种方法可以将给定日期偏移为通过一个简单的电话在一周的开始和结束,但是我一直无法在互联网上找到任何看起来可行的文件。

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.

推荐答案

使用 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)

编辑:

print(start.strftime('%d/%b/%Y'))
print(end.strftime('%d/%b/%Y'))

这篇关于Python:从给定日期开始和结束一周的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆