Python的datetime常用几个操作

jopen 7年前

''''' 日期相关的操作 '''        from datetime import datetime    from datetime import timedelta        DATE_FMT = '%Y-%m-%d'    DATETIME_FMT = '%Y-%m-%d %H:%M:%S'    DATE_US_FMT = '%d/%m/%Y'        '''''   格式化常用的几个参数   Y : 1999   y :99   m : mouth 02 12    M : minute 00-59   S : second   d : day   H : hour   '''        def dateToStr(date):        '''''把datetime类型的时间格式化自己想要的格式'''        return datetime.strftime(date, DATETIME_FMT)        def strToDate(strdate):        '''''把str变成日期用来做一些操作'''        return datetime.strptime(strdate, DATETIME_FMT)         def timeElement():        '''''获取一个时间对象的各个元素'''        now = datetime.today()        print 'year: %s  month: %s  day: %s' %(now.year, now.month, now.day)        print 'hour: %s  minute: %s  second: %s' %(now.hour, now.minute, now.second)        print 'weekday: %s ' %(now.weekday()+1)  #一周是从0开始的        def timeAdd():        '''''       时间的加减,前一天后一天等操作        datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])        参数可以是正数也可以是负数        得到的对象可以加也可以减 乘以数字和求绝对值       '''        atime = timedelta(days=-1)        now = datetime.strptime('2001-01-30 11:01:02', DATETIME_FMT)        print now + atime        print now - abs(atime)        print now - abs(atime)*31        import calendar    def lastFirday():         today = datetime.today()         targetDay = calendar.FRIDAY         thisDay = today.weekday()         de = (thisDay - targetDay) % 7         res = today - timedelta(days=de)         print res              def test():        #print dateToStr(datetime.today())        #print strToDate('2013-01-31 12:00:01')        #timeElement()        #timeAdd()        #lastFirday()            if __name__=='__main__':        test()