Python datetime 模块

目录

一、date类

二、time类

三、datetime类

四、timedelta类,时间加减

五、tzinfo时区类


datatime模块重新封装了time模块,提供更多接口,提供的类有:date, time, datetime, timedelt , tzinfo。

一、date类

datetime.date(year, month, day)

# encoding: utf-8

"""
@author: sunxianpeng
@file: date_test.py
@time: 2019/12/1 16:50
"""
import time
from datetime import date

def static_method_and_attribute():
    print('#####################静态方法和属性######################')
    # date.max、date.min:date对象所能表示的最大、最小日期;
    # date.resolution:date对象表示日期的最小单位。这里是天。
    # date.today():返回一个表示当前本地日期的date对象;
    # date.fromtimestamp(timestamp):根据给定的时间戮,返回一个date对象;
    print('date.max = {}'.format(date.max))
    print('date.min = {}'.format(date.min))
    print('date.today = {}'.format(date.today()))
    print('date.fromtimestamp = {}'.format( date.fromtimestamp(time.time())))
    # date.max = 9999 - 12 - 31
    # date.min = 0001 - 01 - 01
    # date.today = 2019 - 12 - 01
    # date.fromtimestamp = 2019 - 12 - 01

def dynamic_method_and_attribute():
    print('#####################动态方法和属性######################')
    # d1 = date(2011, 06, 03)  # date对象
    # d1.year、date.month、date.day:年、月、日;
    # d1.replace(year, month, day):生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)
    # d1.timetuple():返回日期对应的time.struct_time对象;
    # d1.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
    # d1.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
    # d1.isocalendar():返回格式如(year,month,day)的元组;
    # d1.isoformat():返回格式如'YYYY-MM-DD’的字符串;
    # d1.strftime(fmt):和time模块format相同。
    now = date(2019,12,1)
    tomorrow = now.replace(day=2)
    print('now date = {}'.format(now))#now date = 2019-12-01
    print('tomorrow date = {}'.format(tomorrow))  # tomorrow date = 2019-12-02
    print('timetuple = {}'.format(now.timetuple()))
    print('weekday = {}'.format(now.weekday()))
    print('isoweekday = {}'.format(now.isoweekday()))
    print('isocalendar = {}'.format(now.isocalendar()))
    print('isoformat = {}'.format(now.isoformat()))
    print('strftime = {}'.format(now.strftime('%Y-%m-%d')))
    #now date = 2019-12-01
    # tomorrow date = 2019-12-02
    # timetuple = time.struct_time(tm_year=2019, tm_mon=12, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=335, tm_isdst=-1)
    # weekday = 6
    # isoweekday = 7
    # isocalendar = (2019, 48, 7)
    # isoformat = 2019-12-01
    # strftime = 2019-12-01

if __name__ == '__main__':
    static_method_and_attribute()
    dynamic_method_and_attribute()

二、time类

datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ) 

# encoding: utf-8

"""
@author: sunxianpeng
@file: time_test.py
@time: 2019/12/1 17:02
"""
from datetime import time
def static_method_and_attribute():
    print('#####################静态方法和属性######################')
    # time.min、time.max:time类所能表示的最小、最大时间。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
    # time.resolution:时间的最小单位,这里是1微秒;
    print('time max = {}'.format(time.max))
    print('time min = {}'.format(time.min))
    print('time resolution = {}'.format(time.resolution))
    #time max = 23:59:59.999999
    # time min = 00:00:00
    # time resolution = 0:00:00.000001


def dynamic_method_and_attribute():
    print('#####################动态方法和属性######################')
    # t1 = datetime.time(10, 23, 15)  # time对象
    # t1.hour、t1.minute、t1.second、t1.microsecond:时、分、秒、微秒;
    # t1.tzinfo:时区信息;
    # t1.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]] ):创建一个新的时间对象,用参数指定的时、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变);
    # t1.isoformat():返回型如
    # "HH:MM:SS"
    # 格式的字符串表示;
    # t1.strftime(fmt):同time模块中的format;
    t1 = time(16,23,15)
    t2 = t1.replace(hour=23)
    print('t1 = {}'.format(t1))
    print('hout= {},minute ={},second ={},microsecond={}'.format(t1.hour,t1.minute,t1.second,t1.microsecond))
    print('t2 = {}'.format(t2))
    print('isoformat = {}'.format(t1.isoformat()))
    print('strftime = {}'.format(t1.strftime('%X')))
    # t1 = 16:23: 15
    # hout = 16, minute = 23, second = 15, microsecond = 0
    # t2 = 23:23: 15
    # isoformat = 16:23: 15
    # strftime = 16:23: 15

if __name__ == '__main__':
    static_method_and_attribute()
    dynamic_method_and_attribute()

三、datetime类

datetime相当于date和time结合起来。
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )

# encoding: utf-8

"""
@author: sunxianpeng
@file: datetime_test.py
@time: 2019/12/1 17:12
"""
import time
from datetime import datetime

def static_method_and_attribute():
    print('#####################静态方法和属性######################')
    # datetime.today():返回一个表示当前本地时间的datetime对象;
    # datetime.now([tz]):返回一个表示当前本地时间的datetime对象,如果提供了参数tz,则获取tz参数所指时区的本地时间;
    # datetime.utcnow():返回一个当前utc时间的datetime对象;  # 格林威治时间
    # datetime.fromtimestamp(timestamp[, tz]):根据时间戮创建一个datetime对象,参数tz指定时区信息;
    # datetime.utcfromtimestamp(timestamp):根据时间戮创建一个datetime对象;
    # datetime.combine(date, time):根据date和time,创建一个datetime对象;
    # datetime.strptime(date_string, format):将格式字符串转换为datetime对象;
    print('datetime.max = {}'.format(datetime.max))
    print('datetime.min = {}'.format(datetime.min))
    print('datetime.resolution = {}'.format(datetime.resolution))
    print('datetime.today() = {}'.format(datetime.today()))
    print('datetime.now() = {}'.format(datetime.now()))
    print('datetime.utcnow() = {}'.format(datetime.utcnow()))
    print('datetime.fromtimestamp(time.time()) = {}'.format(datetime.fromtimestamp(time.time())))
    print('datetime.utcfromtimestamp(time.time()) = {}'.format(datetime.utcfromtimestamp(time.time())))
    # datetime.max = 9999-12-31 23:59:59.999999
    # datetime.min = 0001-01-01 00:00:00
    # datetime.resolution = 0:00:00.000001
    # datetime.today() = 2019-12-01 17:16:01.729000
    # datetime.now() = 2019-12-01 17:16:01.729000
    # datetime.utcnow() = 2019-12-01 09:16:01.729000
    # datetime.fromtimestamp(time.time()) = 2019-12-01 17:16:01.729000
    # datetime.utcfromtimestamp(time.time()) = 2019-12-01 09:16:01.729000




def dynamic_method_and_attribute():
    print('#####################动态方法和属性######################')
    # dt = datetime.now()  # datetime对象
    # dt.year、month、day、hour、minute、second、microsecond、tzinfo:
    # dt.date():获取date对象;
    # dt.time():获取time对象;
    # dt.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
    # dt.timetuple()
    # dt.utctimetuple()
    # dt.toordinal()
    # dt.weekday()
    # dt.isocalendar()
    # dt.isoformat([sep])
    # dt.ctime():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));
    # dt.strftime(format)
    dt = datetime.now()
    dt2 = dt.replace(year=2020)
    print('dt = {}'.format(dt))
    print('year={},month={},day={},hour={},minute={},second={},microsecond={},tzinfo={}'.format(
        dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second,dt.microsecond,dt.tzinfo
    ))
    print('dt date = {}'.format(dt.date()))
    print('dt.time = {}'.format(dt.time()))
    print('dt2 = {}'.format(dt2))
    print('dt.timetuple = {}'.format(dt.timetuple()))
    print('dt.utctimetuple() = {}')
    print('dt.toordinal() = {}')
    print('dt.weekday() = {}')
    print('dt.isocalendar() = {}')
    print('dt.isoformat() = {}')
    print('dt.ctime() = {}')
    print('dt.strftime() = {}')
    #dt = 2019-12-01 17:26:34.147000
    # year=2019,month=12,day=1,hour=17,minute=26,second=34,microsecond=147000,tzinfo=None
    # dt date = 2019-12-01
    # dt.time = 17:26:34.147000
    # dt2 = 2020-12-01 17:26:34.147000
    # dt.timetuple = time.struct_time(tm_year=2019, tm_mon=12, tm_mday=1, tm_hour=17, tm_min=26, tm_sec=34, tm_wday=6, tm_yday=335, tm_isdst=-1)
    # dt.utctimetuple() = {}
    # dt.toordinal() = {}
    # dt.weekday() = {}
    # dt.isocalendar() = {}
    # dt.isoformat() = {}
    # dt.ctime() = {}
    # dt.strftime() = {}

if __name__ == '__main__':
    static_method_and_attribute()
    dynamic_method_and_attribute()

四、timedelta类,时间加减

使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法。

# encoding: utf-8

"""
@author: sunxianpeng
@file: timedelta.py
@time: 2019/12/1 17:27
"""
from datetime import datetime
from datetime import timedelta

def datetime_add_or_minus():
    dt = datetime.now()
    # 天数减一天
    dt_minus_1 = dt + timedelta(days=-1)
    dt_minus_2 = dt - timedelta(days=1)
    #计算两个日期的差值
    diff = dt - dt_minus_1
    print('dt = {}'.format(dt))
    print('dt_minus_1 = {}'.format(dt_minus_1))
    print('dt_minus_2 = {}'.format(dt_minus_2))
    print('diff = {}'.format(diff))
    print('diff days = {}'.format(diff.days))
    print('diff total_seconds = {}'.format(diff.total_seconds()))
    #dt = 2019-12-01 17:33:58.560000
    # dt_minus_1 = 2019-11-30 17:33:58.560000
    # dt_minus_2 = 2019-11-30 17:33:58.560000
    # diff = 1 day, 0:00:00
    # diff days = 1
    # diff total_seconds = 86400.0
    
if __name__ == '__main__':
    datetime_add_or_minus()

五、tzinfo时区类

# encoding: utf-8

"""
@author: sunxianpeng
@file: tzinfo.py
@time: 2019/12/1 17:35
"""
from datetime import datetime,timedelta,tzinfo

class UTC(tzinfo):
    def __init__(self,offset=0):
        self._offset = offset
    def utcoffset(self,dt):
        return timedelta(hours=self._offset)
    def tzname(self,dt):
        return "UTC +%s" % self._offset
    def dst(self, dt):
        return timedelta(hours=self._offset)


if __name__ == '__main__':
    # 北京时间
    beijing = datetime(2011, 11, 11, 0, 0, 0, tzinfo=UTC(8))
    print("beijing time:", beijing)
    # 曼谷时间
    bangkok = datetime(2011, 11, 11, 0, 0, 0, tzinfo=UTC(7))
    print("bangkok time", bangkok)
    # 北京时间转成曼谷时间
    print("beijing-time to bangkok-time:", beijing.astimezone(UTC(7)))
    # 计算时间差时也会考虑时区的问题
    timespan = beijing - bangkok
    print("时差:", timespan)
    #beijing time: 2011-11-11 00:00:00+08:00
    # bangkok time 2011-11-11 00:00:00+07:00
    # beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00
    # 时差: -1 day, 23:00:00

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值