天天看點

python time子產品和calendar子產品

time 子產品主要包含了各種提供日期、。時間功能的類和函數,該子產品既提供了把日期、時間格式轉化為字元串的功能,也提供了從字元串恢複日期、時間的功能。

time.asctime():将時間元組或struct_time轉換為時間字元串,如果不指定參數,則預設轉換目前時間

time.ctime():将以秒數為代表的時間轉換為時間字元串

time.time():傳回從1970年1月1日0點整到現在過了多少秒

time.strftime():将時間元組或struct_time對象格式化為指定格式的時間字元串,如果不指定參數,則預設轉換目前時間。

關于calendar子產品,常用方法見代碼:

import calendar
import datetime
import time

print(time.time())  # 擷取從1970-01-01 00:00:00 UTC 到現在時間的秒數
print(time.strftime("%Y-%m-%d %H:%M:%S"))  # 按照指定格式輸出時間
print(time.asctime())  # Mon Apr 15 20:03:23 2019
print(time.ctime(1567404000.6908512))  # Mon Apr 15 20:03:23 2019

print('hello')
# time.sleep(10)  # 讓線程暫停10秒鐘
print('world')

print(datetime.datetime.now())  # 2019-04-15 20:09:05.190113
print(datetime.datetime.now().replace(year=2020))  # 2020-04-15 20:12:37.832657
print(datetime.datetime.now() + datetime.timedelta(weeks=1))  # 2019-04-22 20:11:56.399726


calendar.setfirstweekday(calendar.MONDAY)  # 設定每周起始日期碼。周一到周日分别對應 0 ~ 6
calendar.firstweekday()  # 傳回目前每周起始日期的設定。預設情況下,首次載入calendar子產品時傳回0,即星期一。
c = calendar.calendar(2019)  # 生成2019年的月曆,并且以周日為其實日期碼
print(c)  # 列印2019年月曆
print(calendar.isleap(2000))  # True.閏年傳回True,否則傳回False
count = calendar.leapdays(1996, 2010)  # 擷取1996年到2010年一共有多少個閏年
print(calendar.month(2019, 9))  # 列印2019年3月的月曆