Python 获取自然周的起止日期(年-月-日 00:00:00)

 

 记录下,以备不时之需(网上找了好久,才找个这个比较满意的)

import time

def get_day_begin(ts=time.time(), N=0):
    """
    N为0时获取时间戳ts当天的起始时间戳,N为负数时前数N天,N为正数是后数N天
    24 时(小时)=86400 000 毫秒
    """
    return int(time.mktime(time.strptime(time.strftime('%Y-%m-%d', time.localtime(ts)), '%Y-%m-%d'))) + 86400 * N

def get_week_begin(ts = time.time(),N = 0):
    """
    N为0时获取时间戳ts当周的开始时间戳,N为负数时前数N周,N为整数是后数N周,此函数将周一作为周的第一天
    """
    w = int(time.strftime('%w',time.localtime(ts)))
    return get_day_begin(int(ts - (w-1)*86400)) + N*604800


t=time.time()
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(get_week_begin(t,0))))
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(get_week_begin(t,1))))


 输出结果:

2020-12-28 00:00:00
2021-01-04 00:00:00

 

#来源链接 https://www.oschina.net/code/snippet_46178_13435
posted @ 2020-12-29 23:06  eosclover  Views(1563)  Comments(0Edit  收藏  举报