Python datetime 模块之获取指定的星期几的日期

___tz_zs

以下函数的功能:根据传入的参数(时间,查询星期几),获取某个时间的星期几的日期。

from datetime import datetime
from datetime import timedelta


def get_day(dt_obj, week_day="monday"):
    # 获取当周的星期x
    d = dict(zip(("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"), range(7)))  # datetime 模块中,星期一到星期天对应数字 0 到 6
    delta_hour = timedelta(days=1)  # 改变幅度为 1 天
    while dt_obj.weekday() != d.get(week_day):
        if dt_obj.weekday() > d.get(week_day):
            dt_obj -= delta_hour
        elif dt_obj.weekday() < d.get(week_day):
            dt_obj += delta_hour
        else:
            pass
    return dt_obj.strftime("%Y-%m-%d")

获取本周五的日期

获取当前时间的 datetime 对象,获取本周的星期五的日期。

dt_obj = datetime.now()
print(dt_obj)  # 2019-06-24 00:36:44.325083
print(get_day(dt_obj, "friday"))  # 2019-06-28

获取指定时间点的当周周五

创建特定时间的 datetime 对象,获取指定时间的当周星期五的日期

dt_obj = datetime(year=2019, month=6, day=22)  # 指定时间
dt_obj2 = datetime.strptime("2019-06-22 00:00:00", "%Y-%m-%d %H:%M:%S")  # 或者这样指定
print(dt_obj == dt_obj2)  # True
print(get_day(dt_obj, "friday"))  # 2019-06-21

获取当前时间之后的星期五16点(场景:期货结算时间)

创建指定时间的 datetime 对象,判断其在结算之前或结算之后,当周仍为到达结算时间则获取本周的星期五16点,当周已结算则获取下周的星期五16点。

例一

dt_obj = datetime.strptime("2019-06-21 00:00:00", "%Y-%m-%d %H:%M:%S")
delta_hour = timedelta(days=1)  # 改变幅度为 1 天

if dt_obj.weekday() > 4:
    dt_obj += timedelta(days=7)
else:
    if dt_obj.hour >= 16:
        dt_obj += timedelta(days=7)

print(get_day(dt_obj, "friday"))  # 2019-06-21
print(datetime.strptime(get_day(dt_obj, "friday") + " 16:00:00", "%Y-%m-%d %H:%M:%S"))  # 2019-06-21 16:00:00

例二

dt_obj = datetime.strptime("2019-06-21 16:01:00", "%Y-%m-%d %H:%M:%S")
delta_hour = timedelta(days=1)  # 改变幅度为 1 天

if dt_obj.weekday() > 4:
    dt_obj += timedelta(days=7)
else:
    if dt_obj.hour >= 16:
        dt_obj += timedelta(days=7)

print(get_day(dt_obj, "friday"))  # 2019-06-28
print(datetime.strptime(get_day(dt_obj, "friday") + " 16:00:00", "%Y-%m-%d %H:%M:%S"))  # 2019-06-28 16:00:00

end

你可能感兴趣的:(#,综合)