• python datetime和time的一些疑惑解答 及 获取上年同期、上月等日期


    关于datetime和time有几个疑惑的

    1、datetime.datetime.now()——为什么需要两个datetime才能返回当前时间,同样的time只需要time.localtime()

    后来明白了datetime.datetime.now()——前一个datetime是py文件的名字,中间的datetime是类名,now是方法

    2、格式化输出“%H%M%S”,同样是格式化输出,为什么一个是datetime.datetime.strftime("%H%M%S"),另一个是time.strftime("%H%M%S",time.localtime())

    注意datetime.datetime.strftime是类的方法,注意上图,datetime.datetime.now()返回的是一个datetime的实例化对象。所以可以直接使用datetime.datetime.strftime方法

    而time.strftime()是time模块的方法,注意下图,time.localtime()返回的是time.struct_time对象,这个对象是没有strftime的方法自然报错,用法time.strftime(格式,时间)

    (后来才发现datetime.datetime.strftime(datetime.datetime.now(), "%H%M%S")一样可以)

    注意1、datetime.datetime.strftime(时间,格式)

      2、time.strftime(格式,时间)

    --------------------------------------我是分割线--------------------------------------

     

      

    (以下为个人实现)

    下面继续说最近需要使用到的找上年同期数的一些方法思路。

    使用到datetime.timedelta日期的加减方法,还有calendar.monthrange()获取本月天数的方法

    1、首先分别构造

    本月1号datetime——date_now = datetime.datetime(year=year, month=month, day=1) # 构造本月1号datetime

    本月最后一天的datetime

    2、由于timedelta最大只支持到days参数,本月1号减1就是上月的最后一天,就能得到确定的上月值;本月最后一天+1就是下月的第一天

    3、不断重复调用,返回对应月份即可

    4、没有加上日day的参数,主要是日的不确定性没想明白该怎么弄比较好,比如20160229的上年同期数应该怎么写,如果有思路的伙伴不妨赐教

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Datetime:2018/7/13 0:54
    # Author:Xzs
    
    """
    功能:传入日期类似“201807”格式,年份及月份参数,例如
        date_before("201807", year=1, month=7)——返回上年同期7月前的日期,得到“201612”
        date_after("201807", year=1, month=6)——返回下年同期6月后的日期,得到“202001”
        date_before("201807", year=1, month=0)——上年同期
    """
    
    
    import datetime
    from datetime import timedelta
    import calendar
    
    import sys
    reload(sys)
    sys.setdefaultencoding("utf-8")
    
    
    # 返回传入日期的上月
    def last_one_month(date):
        year = int(date[:4])
        month = int(date[4:])
        date_now = datetime.datetime(year=year, month=month, day=1)  # 构造本月1号datetime
        date_last_month = date_now - timedelta(days=1)  # 上月datetime
        return date_last_month.strftime("%Y%m")
    
    
    # 返回传入日期的下一个月
    def next_one_month(date):
        year = int(date[:4])
        month = int(date[4:])
        a, b = calendar.monthrange(year, month)  # a,b——weekday的第一天是星期几(0-6对应星期一到星期天)和这个月的所有天数
        date_now = datetime.datetime(year=year, month=month, day=b)  # 构造本月1号datetime
        date_next_month = date_now + timedelta(days=1)  # 上月datetime
        return date_next_month.strftime("%Y%m")
    
    
    def date_before(date, year=None, month=None):
        print u"%s年%s月前的日期是:" % (year if year else "-", month if month else "-"),
        if year >= 1:
            month = 12 * year + month
    
        if month > 1:
            for m in range(1, month + 1):
                new_date = last_one_month(date)  # 返回上个月,再以上个月为基础,循环计算得到最终月
                date = new_date
        elif month == 1:
            new_date = last_one_month(date)
        elif month == 0:
            new_date = date
    
        # 如果不输入参数,默认返回本日期
        if year is None and month is None:
            new_date = date
        print new_date
        return new_date
    
    
    def date_after(date, year=None, month=None):
        print u"%s年%s月后的日期是:" % (year if year else "-", month if month else "-"),
        if year >= 1:
            month = 12 * year + month
    
        if month > 1:
            for m in range(1, month + 1):
                new_date = next_one_month(date)  # 返回下个月,再以下个月为基础,循环计算得到最终月
                date = new_date
        elif month == 1:
            new_date = next_one_month(date)
        elif month == 0:
            new_date = date
    
        # 如果不输入参数,默认返回本日期
        if year is None and month is None:
            new_date = date
        print new_date
        return new_date
    
    
    if __name__ == '__main__':
        # next_day("20180501",day=5)
        # last_day("20160301",day=1,year=5)
        date_before("201801")
        date_after("201807")
    

      

     

    发布后看书后发现,对于大多数基本的日期和时间处理,datetime足够,但如果需要更复杂的日期操作,可以使用dateutil模板)

    以下部分为python自带dateutil模块实现年月日的加减,大神造的车子功能基本完善,道行不够未发现,就像车子本来有自动巡航功能,我居然自己找个机械臂去模拟控制,还时不时失灵o(╯□╰)o

    推荐看下《Python Cookbook》第三版中文v3.0.0.pdf,百度自己找资源。新手进阶必备。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Datetime:2018/8/1 19:09
    # Author:Xzs
    
    
    import datetime
    from datetime import timedelta
    from dateutil.relativedelta import relativedelta
    
    
    a = datetime.datetime.now()
    b = datetime.datetime.strftime(a, "%H%M%S")
    print b
    c = relativedelta(years=1,months=1,days=1)
    d = relativedelta(years=-1,months=-1,days=-1)
    print a + c
  • 相关阅读:
    contentEditable
    Web开发工具(插件)收集
    用limit 传变量TO 存储过程解决方案(续)
    ASP.NET1.1和ASP.NET2.0中数据库连接字符串的不同设置
    按比例微缩图片的一段小小的JS代码
    研究下市场上有哪些软件项目/产品,哪些是值得做的?
    Ajax联动下拉框的实现例子
    C#装箱与拆箱
    在VS2005连接SQL2005时不允许远程连接
    联系我们
  • 原文地址:https://www.cnblogs.com/vhills/p/9346399.html
Copyright © 2020-2023  润新知