Python日期時間操作函數詳解

來源:互聯網
上載者:User

處理日誌資料時,經常要對日期進行進行計算,比如日期加上天數、日期相差天數、日期對應的周等計算,本文收集了幾個常用的python日期功能函數,一直更新中。

直接貼代碼(檔案名稱DateUtil.py),函數功能可以直接查看注釋:

 代碼如下 複製代碼

# -*- encoding:utf8 -*-
'''
@author: crazyant
@version: 2013-10-12
'''
import datetime, time

#定義的日期的格式,可以自己改一下,比如改成"$Y年$m月$d日"
format_date = "%Y-%m-%d"
format_datetime = "%Y-%m-%d %H:%M:%S"

def getCurrentDate():
    '''
            擷取當前日期:2013-09-10這樣的日期文字
    '''
    return time.strftime(format_date, time.localtime(time.time()))

def getCurrentDateTime():
    '''
            擷取目前時間:2013-09-10 11:22:11這樣的時間年月日時分秒字串
    '''
    return time.strftime(format_datetime, time.localtime(time.time()))

def getCurrentHour():
    '''
            擷取目前時間的小時數,比如如果當前是下午16時,則返回16
    '''
    currentDateTime=getCurrentDateTime()
    return currentDateTime[-8:-6]

def getDateElements(sdate):
    '''
            輸入日期文字,返回一個結構體組,包含了日期各個分量
            輸入:2013-09-10或者2013-09-10 22:11:22
            返回:time.struct_time(tm_year=2013, tm_mon=4, tm_mday=1, tm_hour=21, tm_min=22, tm_sec=33, tm_wday=0, tm_yday=91, tm_isdst=-1)
    '''
    dformat = ""
    if judgeDateFormat(sdate) == 0:
        return None
    elif judgeDateFormat(sdate) == 1:
        dformat = format_date
    elif judgeDateFormat(sdate) == 2:
        dformat = format_datetime
    sdate = time.strptime(sdate, dformat)
    return sdate

def getDateToNumber(date1):
    '''
            將日期文字中的減號冒號去掉:
            輸入:2013-04-05,返回20130405
            輸入:2013-04-05 22:11:23,返回20130405221123
    '''
    return date1.replace("-","").replace(":","").replace("","")

def judgeDateFormat(datestr):
    '''
            判斷日期的格式,如果是"%Y-%m-%d"格式則返回1,如果是"%Y-%m-%d %H:%M:%S"則返回2,否則返回0
            參數 datestr:日期文字
    '''
    try:
        datetime.datetime.strptime(datestr, format_date)
        return 1
    except:
        pass

    try:
        datetime.datetime.strptime(datestr, format_datetime)
        return 2
    except:
        pass

    return 0

def minusTwoDate(date1, date2):
    '''
            將兩個日期相減,擷取相減後的datetime.timedelta對象
            對結果可以直接存取其屬性days、seconds、microseconds
    '''
    if judgeDateFormat(date1) == 0 or judgeDateFormat(date2) == 0:
        return None
    d1Elements = getDateElements(date1)
    d2Elements = getDateElements(date2)
    if not d1Elements or not d2Elements:
        return None
    d1 = datetime.datetime(d1Elements.tm_year, d1Elements.tm_mon, d1Elements.tm_mday, d1Elements.tm_hour, d1Elements.tm_min, d1Elements.tm_sec)
    d2 = datetime.datetime(d2Elements.tm_year, d2Elements.tm_mon, d2Elements.tm_mday, d2Elements.tm_hour, d2Elements.tm_min, d2Elements.tm_sec)
    return d1 - d2

def dateAddInDays(date1, addcount):
    '''
            日期加上或者減去一個數字,返回一個新的日期
            參數date1:要計算的日期
            參數addcount:要增加或者減去的數字,可以為1、2、3、-1、-2、-3,負數表示相減
    '''
    try:
        addtime=datetime.timedelta(days=int(addcount))
        d1Elements=getDateElements(date1)
        d1 = datetime.datetime(d1Elements.tm_year, d1Elements.tm_mon, d1Elements.tm_mday)
        datenew=d1+addtime
        return datenew.strftime(format_date)
    except Exception as e:
        print e
        return None

def is_leap_year(pyear):
    '''
            判斷輸入的年份是否是閏年
    '''  
    try:                    
        datetime.datetime(pyear, 2, 29)
        return True         
    except ValueError:      
        return False        

def dateDiffInDays(date1, date2):
    '''
            擷取兩個日期相差的天數,如果date1大於date2,返回正數,否則返回負數
    '''
    minusObj = minusTwoDate(date1, date2)
    try:
        return minusObj.days
    except:
        return None

def dateDiffInSeconds(date1, date2):
    '''
            擷取兩個日期相差的秒數
    '''
    minusObj = minusTwoDate(date1, date2)
    try:
        return minusObj.days * 24 * 3600 + minusObj.seconds
    except:
        return None

def getWeekOfDate(pdate):
    '''
            擷取日期對應的周,輸入一個日期,返回一個周數字,範圍是0~6、其中0代表周日
    '''
    pdateElements=getDateElements(pdate)

    weekday=int(pdateElements.tm_wday)+1
    if weekday==7:
        weekday=0
    return weekday

if __name__=="__main__":
    '''
            一些測試代碼
    '''
    print judgeDateFormat("2013-04-01")
    print judgeDateFormat("2013-04-01 21:22:33")
    print judgeDateFormat("2013-04-31 21:22:33")
    print judgeDateFormat("2013-xx")
    print "--"
    print datetime.datetime.strptime("2013-04-01", "%Y-%m-%d")
    print 'elements'
    print getDateElements("2013-04-01 21:22:33")
    print 'minus'
    print minusTwoDate("2013-03-05", "2012-03-07").days
    print dateDiffInSeconds("2013-03-07 12:22:00", "2013-03-07 10:22:00")
    print type(getCurrentDate())
    print getCurrentDateTime()
    print dateDiffInSeconds(getCurrentDateTime(), "2013-06-17 14:00:00")
    print getCurrentHour()
    print dateAddInDays("2013-04-05",-5)
    print getDateToNumber("2013-04-05")
    print getDateToNumber("2013-04-05 22:11:33")

    print getWeekOfDate("2013-10-01")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.