• Python日期时间(datetime.timedelta)


    timedelta类是datetime.py中的一个类,主要处理时间的计算

    其结构如下:

    #class datetime.datetime.timedelta(days=0, seconds=0, microseconds=0,milliseconds=0, minutes=0, hours=0, weeks=0)
    

    生成时间差

    #生成时间差
    today = datetime.date.today()
    td = datetime.timedelta(10) # 10 days, 0:00:00 ,<class 'datetime.timedelta'>
    td = datetime.timedelta(days=-10) # -10 days, 0:00:00 <class 'datetime.timedelta'>
    td = datetime.timedelta(days=-10,hours=5) # -10 days, 5:00:00 <class 'datetime.timedelta'>
    td = datetime.timedelta(days=-10,hours=-5) # -11 days, 19:00:00 <class 'datetime.timedelta'>
    td = datetime.timedelta(days=-10,hours=-5,weeks=1) # -4 days, 19:00:00 <class 'datetime.timedelta'>
    

    计算目标日期

    #计算目标日期
    #计算4天后
    dt = datetime.date.today() # 2020-03-15
    td = datetime.timedelta(days=4)
    print(dt + td)# 2020-03-19
    
    #计算4小时前
    dt = datetime.datetime.today() # 2022-03-15 11:25:28.309209
    td = datetime.timedelta(hours=4)
    print(dt - td) # 2022-03-15 07:25:28.309209
    
    #计算1周以后
    dt = datetime.date.today() # 2020-03-15
    td = datetime.timedelta(weeks=1)
    print(dt + td) # 2022-03-22
    

    根据服务器时间,算本周时间段

    from datetime import date, datetime, timedelta
    
    
    def this_monday(today):
        """
        :function: 获取本周周一日期
        :param_type: datetime
        :return: 返回周一的日期
        :return_type: string
        """
        td = timedelta(days = today.weekday())
        return datetime.strftime(today - td, "%Y-%m-%d")
    
    def this_sunday(today):
        """
        :function: 获取本周周日日期
        :param_type : datetime
        :return: 返回周日日期
        :return_type: string
        """
        td = timedelta(days = 7-today.weekday()-1)
        return datetime.strftime(today + td, "%Y-%m-%d")
    
    today = date.today()
    print(this_monday(today))
    print(this_sunday(today))
    

      

     

  • 相关阅读:
    目标需要分解,行动需要激励
    无助和愤怒都有
    一文搞懂MySQL事务的隔离性如何实现|MVCC
    面试官:请分析一条SQL的执行
    浅谈最长公共子序列引发的经典动态规划问题
    一篇文章带你搞懂InnoDB的索引|结合样例
    Docker
    mac上软件闪退找到错误原因
    前端面试题整理——webpack相关考点
    前端面试题整理——React考点和回答
  • 原文地址:https://www.cnblogs.com/hhs1998/p/16008739.html
Copyright © 2020-2023  润新知