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

發佈了167 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章