python的时间推算写法

示例1

import sys
import os


import datetime
from datetime import timedelta

now = datetime.datetime.now()

#今天
today = now

#昨天
yesterday = now - timedelta(days=1)

#明天
tomorrow = now + timedelta(days=1) #当前季度


#本周第一天和最后一天
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6-now.weekday())

#上周第一天和最后一天
last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)

#本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)

#上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

#本季第一天和最后一天
month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month + 3, 1) - timedelta(days=1)

#上季第一天和最后一天
last_quarter_end = this_quarter_start - timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)

#本年第一天和最后一天
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)

#去年第一天和最后一天
last_year_end = this_year_start - timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)

示例2

def getDataTime(choiceTime=None,choiceType=None):
    '''
    choiceTime = 'yyyy-MM-dd'
    choiceType = 1 or 2 or 3 【周、月、季】
    '''

    if choiceTime:
        choiceTime = datetime.datetime.strptime(choiceTime,"%Y-%m-%d")
        print(choiceTime)
    else:
        choiceTime = datetime.datetime.now()

    if choiceType == 1: #目标时间的上个星期的第一天和最后一天
        startTime = choiceTime - datetime.timedelta(days=choiceTime.weekday()+7)
        endTime =  choiceTime - datetime.timedelta(days=choiceTime.weekday()+1)

    if choiceType == 2: # 目标时间的上个月的第一天和最后一天
        endTime = datetime.datetime(choiceTime.year, choiceTime.month, 1) - datetime.timedelta(days=1)
        startTime = datetime.datetime(endTime.year, endTime.month, 1)


    if choiceType == 3: # 目标时间的 上个季度的第一天和最后一天
        month = (choiceTime.month - 1) - (choiceTime.month - 1) % 3 + 1
        endTime = datetime.datetime(choiceTime.year, month, 1) - datetime.timedelta(days=1)
        startTime = datetime.datetime(endTime.year, endTime.month - 2, 1)

    return {'startTime':startTime.strftime('%Y-%m-%d'),'endTime':endTime.strftime('%Y-%m-%d')}


# print getDataTime(choiceTime='2021-05-30',choiceType=2)
# print getDataTime(choiceType=1)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容