我想根据用户当前时区获得每周的第一天,最后一天。我正在尝试解决,但我找不到在python。向前解决的方法,这里我以两个时差为例。

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),这怎么了?

最佳答案

扩展代码:

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)

08-25 07:13