Python中常用的日期时间函数实例

 代码如下 复制代码

处理日志数据时,经常要对日期进行进行计算,比如日期加上天数、日期相差天数、日期对应的周等计算,本文收集了几个常用的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")

时间: 2024-08-01 03:03:13

Python中常用的日期时间函数实例的相关文章

asp中的一些日期时间函数

本文提供vbscript时间函数的概要介绍,可应对一般应用,具体特殊需求可进一步搜索. date() 获取日期,格式:2004-2-28 time() 获取时间,格式:22:24:59 now() 获取日期和时间 格式: 2005-5-2 22:37:30 d=date() 获取年份:year(d) 获取月份:month(d) 获取日子:day(d) 获取星期几:weekday(d) t=time() 获取小时:hour(t) 获取分钟:minute(t) 获取秒数:second(t) 日期相加

php 中常用的日期处理函数

// date_format2($rs['time'],'%y年%m月%d日%h时%m分%s秒'); function date_format2($string, $format='%b %e, %y', $default_date=null) {     if (substr(php教程_os,0,3) == 'win') {            $_win_from = array ('%e',  '%t',       '%d');            $_win_to   = arr

js开发中常用日期时间函数

js开发中常用日期时间函数 字符串转成日期类型,date.prototype.isleapyear 判断闰年 date.prototype.format 日期格式化 date.prototype.dateadd 日期计算 date.prototype.datediff 比较日期差 date.prototype.tostring 日期转字符串 date.prototype.toarray 日期分割为数组 date.prototype.datepart 取日期的部分信息 date.prototype

SQLserver中常用日期时间函数

统计在数据库中是最常见也是必不可少的,前段时间用Teechat控件使用统计遇到的一些SQL语句整理一下,重点常用函数有datediff()和datepart(),下面大概讲述下这些函数.  代码如下 复制代码 1.一个月第一天的 Select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) 2.本周的星期一 Select DATEADD(wk, DATEDIFF(wk,0,getdate()), 0) 3.一年的第一天 Select DATEADD(yy, DA

Python与SQLite日期时间函数的使法

SQLite的时间函数跟Python的时间函数有些许差别,所以稍做记录,供自己以后查询.     网上有将SQLite官方WIKI内容翻译成中文的文章,大家有兴趣可以搜索一下,我这里单纯记录一下个人比较常用的一些内容. SQLite的五个时间函数: date(日期时间字符串, 修正符, 修正符, ......) time(日期时间字符串, 修正符, 修正符, ......) datetime(日期时间字符串, 修正符, 修正符, ......) julianday(日期时间字符串, 修正符, 修

ORACLE 常用函数——日期/时间函数

---------------------------------------------日期/时间函数----------------------------------------------- --1: SYSDATE 用来得到系统的当前日期 SELECT SYSDATE FROM DUAL; --2: ADD_MONTHS 增加或减去月份 SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20080818','YYYYMMDD'),2), 'YYYY-MM-DD')

PHP中日期时间函数date()用法总结

格式化日期 date() 函数的第一个参数规定了如何格式化日期/时间.它使用字母来表示日期和时间的格式.这里列出了一些可用 的字母: •d - 月中的天 (01-31) •m - 当前月,以数字计 (01-12) •Y - 当前的年(四位数) 您可以在我们的 PHP Date 参考手册中,找到格式参数中可以使用的所有字母. 可以在字母之间插入其他字符,比如 "/"."." 或者 "-",这样就可以增加附加格式了:  代码如下 复制代码 <?

oracle的日期时间函数

经常写 sql 的同学应该会接触到一些 oracle 的日期时间函数, 例如: 财务软件或者人力资源软件需要按照每年, 每季度, 每月, 甚至每个星期来进行统计. 今天闲来没事, 特意从网上整理了一些资料, 以备日后查阅. 一.常用日期数据格式 1. 获取年的最后一位, 两位, 三位, 四位 select to_char(sysdate,'Y') from dual;    -- 获取年的最后一位 select to_char(sysdate,'YY') from dual;    -- 获取年

Excel日期时间函数

   本篇介绍Excel日期时间函数 1.DATE 用途:返回代表特定日期的序列号. 语法:DATE(year,month,day) 参数:year为一到四位,根据使用的日期系统解释该参数.默认情况下,Excel for Windows使用1900日期系统,而Excel for Macintosh使用1904日期系统.Month代表每年中月份的数字.如果所输入的月份大于12,将从指定年份的一月份执行加法运算.Day代表在该月份中第几天的数字.如果 day 大于该月份的最大天数时,将从指定月份的第