您当前的位置:首页 > 计算机 > 编程开发 > Python

python 获取星期几,计算时间差

时间:08-14来源:作者:点击数:
CDSY,CDSY.XYZ

python 获取星期几,计算时间差

导入

import datetime

获取指定日期为星期几

datetime.datetime(2021,9,8).strftime('%w')  #  标准格式输出,周日为0  其余为1-6

datetime.datetime(2021,9,5).isoweekday()    #  返回数字1-7代表周一到周日

datetime.datetime(2021,9,6).weekday()       #  从0开始,例如周一为0  周日为6

获取今日为星期几

同上,改为now()即可
datetime.now().strftime('%w')

python 获取本周,上周,本月,上月,本季;获取一周的日期

import datetime
from datetime import timedelta
 
now = datetime.datetime.now()
 
# 今天
today = now
print('--- today = {}'.format(today))
 
# 昨天
yesterday = now - timedelta(days=1)
print('--- yesterday = {}'.format(yesterday))
 
# 明天
tomorrow = now + timedelta(days=1)
print('--- tomorrow = {}'.format(tomorrow))
 
# 当前季度
now_quarter = now.month / 3 if now.month % 3 == 0 else now.month / 3 + 1
print('--- now_quarter = {}'.format(now_quarter))
 
# 本周第一天和最后一天
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6 - now.weekday())
print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
 
# 上周第一天和最后一天
last_week_start = now - timedelta(days=now.weekday() + 7)
last_week_end = now - timedelta(days=now.weekday() + 1)
print('--- last_week_start = {} last_week_end = {}'.format(last_week_start, last_week_end))
 
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
 
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
 
# 本季第一天和最后一天
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)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
print('--- this_quarter_start = {} this_quarter_end = {}'.format(this_quarter_start, this_quarter_end))
 
# 上季第一天和最后一天
last_quarter_end = this_quarter_start - timedelta(days=1)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)
print('--- last_quarter_start = {} last_quarter_end = {}'.format(last_quarter_start, last_quarter_end))
 
# 本年第一天和最后一天
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
print('--- this_year_start = {} this_year_end = {}'.format(this_year_start, this_year_end))
 
# 去年第一天和最后一天
last_year_end = this_year_start - timedelta(days=1)+ datetime.timedelta(
	hours=23, minutes=59, seconds=59)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)
print('--- last_year_start = {} last_year_end = {}'.format(last_year_start, last_year_end))
# 获取一周的日期
    now_time = datetime.datetime.now()  # 获取当前时间
    day_num = now_time.isoweekday()  # 当前天是这周的第几天
    week_start = ((now_time - datetime.timedelta(days=day_num)) + datetime.timedelta(
        days=1)).date()  # 计算当前天所在周周一 格式为yyyy-MM-dd
    week_end = ((now_time - datetime.timedelta(days=day_num)) + datetime.timedelta(
        days=7)).date()  # 计算当前天所在周周天 格式为yyyy-MM-dd
    print(week_end)
    week_e = ((now_time - datetime.timedelta(days=day_num)) + datetime.timedelta(
        days=7))  # 计算当前天所在周周天 格式为yyyy-MM-dd 12:01:13.026315
    week_s = ((now_time - datetime.timedelta(days=day_num)) + datetime.timedelta(
        days=1))  # 计算当前天所在周周一 格式为yyyy-MM-dd 12:01:13.026315
    # while week_s <= week_e:  # 循环输出周一至周五的每天日期格式yyyy-MM-dd
        # print(week_s.date())
    # week_s = week_s + datetime.timedelta(days=1)


    create_time__range = (week_start, week_end)  # 范围(周一,周五)可用于数据库日期范围查询
    print(create_time__range)

计算时间差

# coding=utf-8
import datetime


def time_diff(start_time, end_time, diff_type="second"):
    """
    计算时间差
    :param datetime.datetime start_time: 起始时间
    :param datetime.datetime end_time: 结束时间
    :param str diff_type: 时间类型
    :return: 相差多少个时间类型
    """
    date_dict = {
        "second": 1,
        "minute": 60,
        "hour": 3600,
        "day": 86400
    }
    diff = (end_time - start_time).total_seconds()
    if diff_type in date_dict:
        return diff // date_dict[diff_type]
    else:
        raise KeyError("diff_type must in %s" % date_dict.keys())


if __name__ == '__main__':
    print(time_diff(datetime.datetime.strptime('2021-10-07 21:51:00', '%Y-%m-%d %H:%M:%S')
                    , datetime.datetime.strptime('2021-10-07 21:54:00', '%Y-%m-%d %H:%M:%S')))

未来7天

list(map(lambda x: x.strftime('%Y-%m-%d')
                        , [datetime.now().date() + timedelta(days=i)for i in range(1, 8)]))



def _future_seven_date() -> list:
    '''未来七天的日期'''
    return list(map(lambda x: x.strftime('%Y-%m-%d')  # 获取未来7天的日期
                    , [datetime.now().date() + timedelta(days=i) for i in range(1, 8)]))

def _future_seven_week(_date_list: list) -> list:
    '''根据日期获取未来7天的星期'''
    week_tuple: tuple = ('周一', '周二', '周三', '周四', '周五', '周六', '周日')
    return [week_tuple[datetime(*list(map(lambda x: int(x),  # 吧日期转为星期
                                          i.split('-')))).weekday()] for i in _date_list]

根据日期区间找区间内所有日期

import datetime

'''获取指定日期范围所有日期列表'''


def date_range(beginDate, endDate):
    dates = []
    dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
    date = beginDate[:]
    while date <= endDate:
        dates.append(date)
        dt = dt + datetime.timedelta(1)
        date = dt.strftime("%Y-%m-%d")
    return dates


date_list = date_range("2022-02-01", "2022-05-15")
print(date_list)
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐