如何使用基于星期几的日期时间创建日期?

时间:2016-07-02 06:40:21

标签: python date datetime

我想使用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.

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分: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

```

答案 1 :(得分:0)

完整解决方案:

inline-source-map

或使用我的lib t77_date并使用:

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)