我希望根据用户当前时区获得第一个星期一的最后一天。我试图解决,但我找不到前进的方法来解决python.here我已采取两个差异时区为例。
from datetime import datetime, date, timedelta
from pytz import timezone
tz1 = timezone('utc')
tz2 = timezone('Asia/Kolkata')
tz3 = timezone('America/Los_Angeles')
dt1 = datetime.now(tz=tz1)
dt2 = datetime.now(tz=tz2)
dt3 = datetime.now(tz=tz3)
start_of_week = dt1+timedelta(days=0-dt1.weekday())
end_of_week = dt1+timedelta(days=6-dt1.weekday())
print(start_of_week)
print(end_of_week)
start_of_week2 = dt2+timedelta(days=0-dt2.weekday())
end_of_week2 = dt2+timedelta(days=6-dt2.weekday())
print(start_of_week2)
print(end_of_week2)
start_of_week3 = dt3+timedelta(days=0-dt3.weekday())
end_of_week3 = dt3+timedelta(days=6-dt3.weekday())
print(start_of_week3)
print(end_of_week3)
输出:
2017-10-02 09:21:32.666920+00:00
2017-10-08 09:21:32.666920+00:00
2017-10-02 14:51:32.666920+05:30 # not right
2017-10-08 14:51:32.666920+05:30 # not right
2017-10-02 02:21:32.666920-07:00 # not right
2017-10-08 02:21:32.666920-07:00 # not right
我住在Asia/kolkata
,本周开始为Oct 01 (Sunday)
,周末为Oct 07 (Saturday)
,这里有什么问题?
答案 0 :(得分:2)
扩展您的代码:
from datetime import datetime, date,timedelta
from pytz import timezone
tz1 = timezone('utc')
tz2 = timezone('Asia/Kolkata')
tz3 = timezone('America/Los_Angeles')
dt1 = datetime.now(tz=tz1)
dt2 = datetime.now(tz=tz2)
print(dt1)
print(dt2)
start_of_week = dt1+timedelta(days=0-dt1.weekday())
end_of_week = dt1+timedelta(days=6-dt1.weekday())
print(start_of_week)
print(end_of_week)
答案 1 :(得分:0)
我正在扩大chakris的回答:
已更新由于一周可以在同一天开始或结束,当您输入星期日和周日开始时,您有两个选择。
也许您可以更改代码以满足您的需求。
SELECT User, Host FROM mysql.user;
返回
from datetime import datetime, date,timedelta
from pytz import timezone
def week_startandend(dt_,weekstart=0):
"""Returns tuple with start date of week and end day of week."""
index = (dt_.weekday() + (7-weekstart % 7) ) % 7
# Calculate start and end
start = dt_+timedelta(days=0-index)
end = dt_+timedelta(days=6-index)
# if week doesnt start on the same day we can return
if index != 0:
return {"start":start.date(),"end":end.date()}
# else we need to calculate the other option
else:
start2 = dt_+timedelta(days=-7)
end2 = dt_
return {"start1":start.date(),"end1":end.date(),
"start2":start2.date(),"end2":end2.date()}
tz1 = timezone('utc')
tz2 = timezone('Asia/Kolkata')
dt1 = datetime.now(tz=tz1)
dt2 = datetime.now(tz=tz2)
print(week_startandend(dt1)) # defaults to 0
print(week_startandend(dt2,weekstart=6)) # 6 = sunday
在[352]中: