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

來源:互聯網
上載者:User

標籤:src   解答   為什麼   時間   range   div   ret   檔案   就是   

關於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.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 datetimefrom datetime import timedeltaimport calendarimport sysreload(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_datedef 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_dateif __name__ == ‘__main__‘:    # next_day("20180501",day=5)    # last_day("20160301",day=1,year=5)    date_before("201801")    date_after("201807")

  

  

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.