前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python时间处理之date

python时间处理之date

作者头像
py3study
发布2020-01-10 15:12:08
8420
发布2020-01-10 15:12:08
举报
文章被收录于专栏:python3python3
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
date的用法 (test_datetime.py)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Created by bixiaofan <wirelessqa@163.com> 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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档