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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM