1. 程式人生 > >python datetime和time的一些疑惑解答 及 獲取上年同期、上月等日期

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

light struct color enc efault strftime 第一天 truct sys

關於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 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")

  

  

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