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

你可能感兴趣的:(玩转,Python)