Python 中 time 和 datetime 模塊

理論知識

1、UTC 時間

UTC time Coordinated Universal Time,世界協調時,又稱格林尼治天文時間、世界標準時間。與UTC time對應的是各個時區的local time,也就是本地時間,例如我們的北京時間。

2、時間戳

# '2008-02-21 17:58:33' 
1203587913.0

時間戳表示的是從 1970 年 1 月 1 日 00:00:00 開始按秒計算的偏移量 ,表現爲一個 float 類型

3、時間元組

時間元組,共有九個元素組。時間戳和格式化時間字符串之間的轉化必須通過時間元組纔行,所以時間元組是 3 種時間表示的中心。

# '2008-02-21 17:58:33' 
time.struct_time(tm_year=2008, tm_mon=2, tm_mday=21, tm_hour=17, tm_min=58, tm_sec=33, tm_wday=3, tm_yday=52, tm_isdst=-1)

time 常用方法

import time


print("---------獲取時間---------")
print(time.time()) # 獲取當前時間戳
print(int(time.time()))
print(time.localtime()) # 獲取本地時間元組
print(time.gmtime()) # 獲取世界標準時間元組
#print(time.localtime(1574239905)) # 也是時間戳轉時間元組
print(time.gmtime(1574239905)) # 如果傳入了時間戳,就是把時間戳轉換成時間元組

print("---------格式化時間---------")
print("------時間元組--->日期字符串------")
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 格式化當前時間
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) # 格式化制定時間
print(time.strftime('%Y-%m-%d')) # '%y-%m-%d' 19-11-20
print(time.strftime('%H:%M:%S')) # 
print(time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年',m='月',d='日',h='時',f='分',s='秒')) # 解決中文報錯問題

print("------日期字符串--->時間元組------")
print(time.strptime('2019-11-20 17:27:52', '%Y-%m-%d %H:%M:%S'))

print("------時間元組--->時間戳------")
print(time.mktime(time.localtime()))

輸出

---------獲取時間---------
1574243913.5221558
1574243913
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=20, tm_hour=17, tm_min=58, tm_sec=33, tm_wday=2, tm_yday=324, tm_isdst=0)
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=20, tm_hour=9, tm_min=58, tm_sec=33, tm_wday=2, tm_yday=324, tm_isdst=0)
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=20, tm_hour=8, tm_min=51, tm_sec=45, tm_wday=2, tm_yday=324, tm_isdst=0)
---------格式化時間---------
------時間元組--->日期字符串------
2019-11-20 17:58:33
2019-11-20 17:58:33
2019-11-20
17:58:33
20191120175833------日期字符串--->時間元組------
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=20, tm_hour=17, tm_min=27, tm_sec=52, tm_wday=2, tm_yday=324, tm_isdst=-1)
------時間元組--->時間戳------
1574243913.0

datetime 常用方法

datetime 模塊是 time 模塊的進一步封裝,對用戶更加友好,在時間各屬性的獲取上回更加方便一些,當然,在效率上會略微低一些。datetime 模塊的功能主要都幾種在 datetime、date、time、timedelta、tzinfo 五個類中。這五個類功能如下表所示:

類名 功能
date 提供日期(年、月、日)的處理
time 提供時間(時、分、秒)的處理
datetime 同時提供對日期和時間的處理
timedelta 兩個 date、time、datetime 實例之間的時間間隔(時間加減運算)
tzinfo 時區信息

這裏只介紹比較常用的 datetime 類

類方法 / 屬性名稱 描述
datetime.today() 返回一個表示當前本期日期時間的 datetime 對象
datetime.now([tz]) 返回指定時區日期時間的 datetime 對象,如果不指定 tz 參數則結果同上
datetime.utcnow() 返回當前 utc 日期時間的 datetime 對象
datetime.fromtimestamp(timestamp[, tz]) 根據指定的時間戳創建一個 datetime 對象
datetime.utcfromtimestamp(timestamp) 根據指定的時間戳創建一個 datetime 對象
datetime.combine(date, time) 把指定的 date 和 time 對象整合成一個 datetime 對象
datetime.strptime(date_str, format) 將時間字符串轉換爲 datetime 對象
對象方法 / 屬性名稱 描述
dt.year, dt.month, dt.day 年、月、日
dt.hour, dt.minute, dt.second 時、分、秒
dt.microsecond, dt.tzinfo 微秒、時區信息
dt.date() 獲取 datetime 對象對應的 date 對象
dt.time() 獲取 datetime 對象對應的 time 對象, tzinfo 爲 None
dt.timetz() 獲取 datetime 對象對應的 time 對象,tzinfo 與 datetime 對象的 tzinfo 相同
dt.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) 生成並返回一個新的 datetime 對象,如果所有參數都沒有指定,則返回一個與原 datetime 對象相同的對象
dt.timetuple() 返回 datetime 對象對應的時間元組
dt.utctimetuple() 返回 datetime 對象對應的 utc 時間元組
dt.toordinal() 返回日期是是自 0001-01-01 開始的第多少天
dt.weekday() 返回日期是星期幾,[0, 6],0 表示星期一
dt.isocalendar() 返回日期是星期幾,[1, 7], 1 表示星期一
dt.isoformat([sep]) 返回一個‘% Y-% m-% d
dt.ctime() 等價於 time 模塊的 time.ctime (time.mktime (d.timetuple ()))
dt.strftime(format) 返回指定格式的時間字符串
now1 = datetime.datetime.now() # 獲取當前時間
now2 = time.strftime('%Y-%m-%d %H:%M:%S')
print(now1)
print(now2)

now = datetime.datetime.now()
d1 = now - datetime.timedelta(hours=1) # 獲取前一個小時
d2 = now - datetime.timedelta(days=1) # 獲取前一天
print(now)
print(d1)
print(d2)

輸出

2019-11-20 23:18:38.871579
2019-11-20 23:18:38
2019-11-20 23:18:38.871579
2019-11-20 22:18:38.871579
2019-11-19 23:18:38.871579
# datetime對象轉換成時間戳
dt = datetime.datetime.now()
print(time.mktime(dt.timetuple()))
# 時間戳轉換成datetime對象
sjc_time = time.time()
print(datetime.datetime.fromtimestamp(sjc_time))

輸出

1574263122.0
2019-11-20 23:18:42.398782

python 日期校驗

import time

def datetime_verify(date):
    """判斷是否是一個有效的日期字符串"""
    try:
        if ":" in date:
            time.strptime(date, "%Y-%m-%d %H:%M:%S")
        else:
            time.strptime(date, "%Y-%m-%d")
        return True
    except Exception as e:
        print(e)
        return False

參考鏈接:

https://www.cnblogs.com/chenhuabin/p/10099766.html

https://www.jb51.net/article/164828.htm

https://blog.csdn.net/gymaisyl/article/details/90644222

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章