我的应用程序中包含逻辑,要求根据中午的最后一个星期一进行一些汇总。现在,我已经开始考虑最后一个星期一,而不考虑时间。我这样做是这样的:
today = datetime.now()
last_monday = today - timedelta(days=today.weekday())
last_monday = last_monday.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc)
如果从星期一凌晨12点开始,则此方法有效。我需要自上个星期一(UTC)下午12点(从今天起的最后一个星期一)以来发生的所有事情。有谁知道如何做到这一点?我需要这个,因为我想做类似的事情
last_monday_at_12pm = *answer*
if last_monday_at_12pm < date_to_compare:
* then do something *
答案 0 :(得分:0)
如果您使用的是Python 3.8,则可以为此使用isocalendar
功能:
from datetime import datetime
def get_lastmonday_1200(dtobj):
# check if input date is monday:
week_offset = 1 if dtobj.weekday() == 0 else 0
# use isocalendar() to get week and day number:
year, week, _ = dtobj.isocalendar()
# create the datetime object "last monday",
# note that monday is day=1 (not 0):
return datetime.fromisocalendar(year, week-week_offset, 1).replace(hour=12, tzinfo=dtobj.tzinfo)
print(get_lastmonday_1200(datetime(2020, 3, 3))) # expect 2020-3-2 12:00
# 2020-03-02 12:00:00
print(get_lastmonday_1200(datetime(2020, 3, 8))) # expect 2020-3-2 12:00
# 2020-03-02 12:00:00
print(get_lastmonday_1200(datetime(2020, 3, 9))) # expect 2020-3-2 12:00
# 2020-03-02 12:00:00
答案 1 :(得分:-1)
下面的代码段返回现在的最后一个星期一。
import datetime
now = datetime.datetime.now()
last_monday = now - datetime.timedelta(days=now.weekday())
与上述相同,您可以获取每个特定日期和时间的最后一个星期一。例如,考虑以下代码段:
import datetime
moment = datetime.datetime(year=2019, month=12, day=13)
last_monday = moment - datetime.timedelta(days=moment.weekday())
以上代码段返回2019/12/13的最后一个星期一的00:00。因此,对于您的情况,您可以这样做:
import datetime
moment = datetime.datetime(
year=2019, month=12, day=13,
hour=12, minute=0, second=0, microsecond=0
)
last_monday_at_12pm = moment - datetime.timedelta(days=moment.weekday())
if last_monday_at_12pm < date_to_compare:
# do something
pass
最后,您可以像今天这样从今天获得最后一个星期一:
import datetime
now = datetime.datetime.now()
today_noon = now.replace(hour=12, minute=0, second=0, microsecond=0)
last_monday_at_12pm = today_noon - datetime.timedelta(days=today_noon.weekday())
if last_monday_at_12pm < date_to_compare:
# do something
pass