我想用datetime
写一段代码,这样,如果datetime.now()
是星期六或星期五下午4点以后,创建一个日期时间对象在下午4点通过的星期五。
我已经完成了以下内容:
from datetime import datetime
datenow = datetime.now()
if datenow.isoweekday() == 6 or (datenow.isoweekday() in [5] and datenow.hour >=16):
## change datenow to the passing friday at 4pm.
有人能帮帮我吗?
完整解决方案:
def set_prev_iso_week_day(val, iso_week_day):
"""
Set ISO week day.
New date will be less or equal than input date.
:param val: datetime or date
:type val: datetime.datetime | datetime.date
:param iso_week_day: ISO week day to set
:type iso_week_day: int
:return: datetime.datetime | datetime.date
"""
if val.isoweekday() == iso_week_day:
return val
diff = iso_week_day - val.isoweekday()
diff = -diff if diff < 0 else 7 - diff
val -= timedelta(days=diff)
return val
datenow = set_prev_iso_week_day(datenow, 5).replace(hour=16,minute=0,second=0,microsecond=0)
或使用我的lib t77_date和使用:
from t77_date.constants import ISO_FRIDAY
from t77_date.datetime import set_prev_iso_week_day
datenow = set_prev_iso_week_day(datenow, ISO_FRIDAY).replace(hour=16,minute=0,second=0,microsecond=0)
试试这个:
from datetime import timedelta
def mod_time(datenow):
if datenow.isoweekday() in [6,7]:#for Saturday or Sunday
print datenow
datenow -= timedelta(days=datenow.isoweekday()-5) #Going back to Friday
print datenow
datenow = datenow.replace(hour=16,minute=0,second=0,microsecond=0) #Making 4pm
print datenow
return datenow
' ' '