1. 程式人生 > >datetime模組筆記

datetime模組筆記

datetime
-處理時間和日期的標準庫
時間戳:從1970年1月1日0時0分0秒,到當前時間的秒數,浮點數,到毫秒
模組:
-date 日期物件, 常用的屬性 year,month,day
-time 時間物件, hour, minute, second, microsecond
-datetime 日期時間物件
-timedelta 時間間隔,兩個時間之間的長度

"""
 建立  datetime 中的常用物件
"""
#基本用法
from datetime import time,date,datetime,timedelta

d = date(2018,5,6)
print(d,type(d))

t = time(hour=22,minute=34,second=23,microsecond=4567)
print(t,type(t))

dt = datetime(2012,2,22,23,5)
print(dt,type(dt))

td = timedelta(hours=33443.4)
print(td,type(td))

"""
datetime.datetime日期時間物件的常用方法
"""
now = datetime.now()
print(now,type(now))


time_str = now.strftime('%Y-%m-%d,%H:%M:%S,%A %B')
print(time_str,type(time_str))


# dt = datetime.strptime('2018/11/13', '%Y/%m/%d')  
# print(dt, type(dt))

print(now.timestamp())  # 浮點數
# 時間戳-》datetime
dt1 = datetime.fromtimestamp(1542373647.00759)
print(dt1, type(dt1))

#  date time datetime 都是 不可變物件
print({now: 'xinlan'})

"""
時間格式化(記憶)
    %Y  Year with century as a decimal number. 2018 18
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.  星期的簡寫
    %A  Locale's full weekday name.         星期的全稱
    %b  Locale's abbreviated month name.    月的簡寫
    %B  Locale's full month name.           月的全寫
    %c  Locale's appropriate date and time representation.
        # Fri Nov 16 21:18:16 2018
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
    
"""

'''
時間運算
'''
today = datetime.now().date()
print(today,type(today))

tomorrow = today +timedelta(days=1)
print(tomorrow,type(tomorrow))

執行結果:
在這裡插入圖片描述
注意時間是不可變物件,tuple表示。