广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python时间处理之date
  • 411
分享到

python时间处理之date

时间pythondate 2023-01-31 01:01:29 411人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

#!/usr/bin/python # -*- coding:utf-8 -*- """ date的用法 (test_datetime.py) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#!/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

--结束END--

本文标题: python时间处理之date

本文链接: https://www.lsjlt.com/news/184456.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作