python時間処理のdate


#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
date    (test_datetime.py)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Created by bixiaofan  on 2018/1/24 at   9:46
"""

import time

from datetime import date


def test_datetime_date():
    #### 1. date          

    # date           :9999-12-3
    assert str(date.max) == "9999-12-31"
    # date           : 0001-01-01
    assert str(date.min) == "0001-01-01"
    #              date  : 2012-09-12
    print('date.today(): {}'.format(date.today()))
    #  Gregorian       date  (Gregorian Calendar :        ,        ,         ):
    # 1347442385.972   2012-09-12
    print('date.fromtimestamp(): {}'.format(date.fromtimestamp(time.time())))

    #### 2. date          

    #        
    now = date(2012, 9, 17)
    assert now.year == 2012
    assert now.month == 9
    assert now.day == 17

    # date.replace(year, month, day):          
    #        , ,           。(         )
    tomorrow = now.replace(day=18)
    nextmonth = now.replace(month=10)
    nextyear = now.replace(year=2013)

    assert str(tomorrow) == "2012-09-18"
    assert str(nextyear) == "2013-09-17"
    assert str(nextmonth) == "2012-10-17"

    #      ,    ==0 ...      == 6
    assert now.weekday() == 0

    #         ,    ==1 ...      == 7
    assert now.isoweekday() == 1

    #      (year,month,day)   ;
    assert now.isocalendar() == (2012, 38, 1)

    #      'YYYY-MM-DD’    ;
    assert str(now.isoformat()) == '2012-09-17'

    #### 3.     
    now = date.today()  #   
    tomorrow = now.replace(day=now.day + 1)  #   
    print("now: {} tomorrow: {}".format(now, tomorrow))

    #        
    delta = tomorrow - now
    assert str(delta) == "1 day, 0:00:00"
    assert now + delta == tomorrow
    assert tomorrow > now