Python學習之——時間模塊
- 參考
- time 模塊
- 常見接口
- datetime 模塊
- 常見接口
- calendar 模塊
- 常見接口
- 示例
參考
Python datetime模塊詳解、示例
搞定Python時區的N種姿勢
calendar – 日歷相關
time 模塊
在Python中,通常有這幾種方式來表示時間:
1)時間戳
2)格式化的時間字符串
3)元組(struct_time)共九個元素。
UTC(Coordinated Universal Time,世界協調時):即格林威治天文時間,世界標準時間,在中國為UTC+8。
DST(Daylight Saving Time:即夏令時。
時間戳(timestamp):時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。
元組(struct_time):struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。
下面列出這種方式元組中的幾個元素:
索引(Index) | 屬性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(時) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 61 |
6 | tm_wday(weekday) | 0 - 6(0表示周日) |
7 | tm_yday(一年中的第幾天) | 1 - 366 |
8 | tm_isdst(是否是夏令時) | 默認為-1 |
常見接口
import time# 返回當前UTC時間的時間戳(從1970年1月1日00:00:00開始按秒計算的偏移量)
time.time()# 和localtime()類似,gmtime()是將一個時間戳轉換為UTC-0時區的struct_time。
time.gmtime([secs])# 將一個時間戳轉換為當前本地時區的struct_time。secs參數未提供,返回當前本地時區的當前時間struct_time
time.localtime([secs])# localtime()的反函數,將一個struct_time轉化為時間戳。
# 參數是 struct_time 或者完整的9元組 ,注意參數是當前本地時區的struct_time,而不是UTC-0時區
time.mktime(t)# 把一個表示時間的struct_time或者完整的9元組轉化為格式化的時間字符串。
# 如果t未指定,將傳入time.localtime()
time.strftime(format[, t])# strftime()的逆操作, 把一個格式化時間字符串轉化為struct_time
time.strptime(string[, format])# 把一個表示時間的struct_time或者完整的9元組表示為:'Sat Dec 9 23:16:45 2023'。這種形式
# 如果沒有參數,將會將time.localtime()作為參數傳入
time.asctime([t])# 把一個時間戳轉化為time.asctime()的形式。
# 如果參數未給或者為None的時候,將會默認time.time()為參數
time.ctime([secs])# 線程推遲指定的時間運行,單位為秒。
time.sleep(secs)# 在UNIX系統上,clock()返回的是秒表示的時間戳
# 在WINDOWS中,第一次調用,返回的是進程運行的實際時間。而第二次之后的調用是自第一次調用以后到現在的運行時間。
time.clock()
示例
import time
print(f'time.time():{time.time()}')
print(f'time.gmtime():{time.gmtime()}')
print(f'time.localtime():{time.localtime()}')
print(f'time.strftime("%Y/%m/%d/ %H:%M:%S", time.localtime()):{time.strftime("%Y/%m/%d/ %H:%M:%S", time.localtime())}')
print(f'time.asctime:{time.asctime()}')# 結果
time.time():1702135670.389908
time.gmtime():time.struct_time(tm_year=2023, tm_mon=12, tm_mday=9, tm_hour=15, tm_min=27, tm_sec=50, tm_wday=5, tm_yday=343, tm_isdst=0)
time.localtime():time.struct_time(tm_year=2023, tm_mon=12, tm_mday=9, tm_hour=23, tm_min=27, tm_sec=50, tm_wday=5, tm_yday=343, tm_isdst=0)
time.strftime("%Y/%m/%d/ %H:%M:%S", time.localtime()):2023/12/09/ 23:27:50
time.asctime:Sat Dec 9 23:27:50 2023
datetime 模塊
python datetime time 時間模塊
搞定Python時區的N種姿勢
datetime模塊中包含如下類:
類名 | 功能說明 |
---|---|
date | 日期對象,常用的屬性有year, month, day |
time | 時間對象 |
datetime | 日期時間對象,常用的屬性有hour, minute, second, microsecond |
datetime_CAPI | 日期時間對象C語言接口 |
timedelta | 時間間隔,即兩個時間點之間的長度 |
tzinfo | 時區信息對象 |
datetime模塊中包含的常量
datetime.MAXYEAR # 返回能表示的最大年份9999
datetime.MINYEAR # 返回能表示的最小年份1
常見接口
from datetime import datetime, timedelta, tzinfo# 獲取當前utc-0時區的時間
datetime.utcnow()
# 由時間戳返回本地時間datetime
datetime.fromtimestamp
# 由時間戳返回utc時間datetime
datetime.utcfromtimestamp
calendar 模塊
calendar – 日歷相關
Python-標準庫calendar的使用
提供日歷功能
常見接口
import calendarif __name__ == "__main__":cc = calendar.Calendar(0)one_weekday = []for index, dt in enumerate(cc.itermonthdates(2023, 12)):if index != 0 and index % 7 == 0:print(''.join(one_weekday))one_weekday.clear()one_weekday.append(f'{dt} ')# 結果
2023-11-27 2023-11-28 2023-11-29 2023-11-30 2023-12-01 2023-12-02 2023-12-03
2023-12-04 2023-12-05 2023-12-06 2023-12-07 2023-12-08 2023-12-09 2023-12-10
2023-12-11 2023-12-12 2023-12-13 2023-12-14 2023-12-15 2023-12-16 2023-12-17
2023-12-18 2023-12-19 2023-12-20 2023-12-21 2023-12-22 2023-12-23 2023-12-24
示例
一些常見的時間轉換函數封裝
# -*- coding: utf-8 -*-
import time
from datetime import datetime, timezone, timedeltaTIME_FORMAT_STR = "%Y/%m/%d/ %H:%M:%S"
DAY_SECOND = 86400
HOUR_SECOND = 3600
MINUTE_SECOND = 60def datetime_to_str(datetime_obj: datetime, format_str=TIME_FORMAT_STR) -> str:return datetime_obj.strftime(format_str)def str_to_datetime(time_str: str, format_str=TIME_FORMAT_STR) -> datetime:return datetime.strptime(time_str, format_str)def datetime_to_timestamp(datetime_obj: datetime) -> float:return time.mktime(datetime_obj.timetuple())def timestamp_to_str(timestamp: float, format_str=TIME_FORMAT_STR) -> str:return time.strftime(format_str, time.localtime(timestamp))def str_to_timestamp(time_str: str, format_str=TIME_FORMAT_STR) -> float:"""time.gmtime([secs]): 將一個時間戳轉換為UTC-0時區的struct_time。time.localtime([secs]): 將一個時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準time.mktime: localtime()的反函數,將一個struct_time轉化為時間戳,注意參數是使用本地時區的_TimeTuple | struct_time,而不是UTC-0時區"""datetime_obj: datetime = str_to_datetime(time_str, format_str)return time.mktime(datetime_obj.timetuple())def get_local_date_str(timestamp: float) -> str:"""將一個時間戳轉換為當前本地時區的日期字符串"""# 將一個時間戳轉換為當前時區的struct_timetime_struct: time.struct_time = time.localtime(int(timestamp))ret: str = time.strftime(TIME_FORMAT_STR, time_struct)return retdef get_local_date_str_custom1(timestamp: float, HMS_FMT="%H:%M:%S") -> str:time_struct: time.struct_time = time.localtime(int(timestamp))input_day = int(timestamp) / DAY_SECONDcur_day = int(time.time()) / DAY_SECONDif input_day == cur_day:return time.strftime(HMS_FMT, time_struct)else:return time.strftime(TIME_FORMAT_STR, time_struct)def get_now_time_str(is_local: bool = True, timezone_num: int = 0) -> str:if is_local:# 當前本地時區datetime_obj: datetime = datetime.now()else:# utc-0 時區# utc_0_datetime: datetime = datetime.utcnow()# timezone_num=0: utc-0 時區; timezone_num=2: utc-2 時區datetime_obj: datetime = datetime.now(timezone(timedelta(hours=timezone_num)))return datetime_to_str(datetime_obj)def timestamp_to_utc_str(timestamp: float, format_str=TIME_FORMAT_STR) -> str:"""時間戳轉utc-0時區的時間"""datetime_obj: datetime = datetime.utcfromtimestamp(timestamp)return datetime_obj.strftime(format_str)def timestamp_to_local_str(timestamp: float, format_str=TIME_FORMAT_STR) -> str:"""時間戳轉當前本地時區的時間"""datetime_obj: datetime = datetime.fromtimestamp(timestamp)return datetime_obj.strftime(format_str)def get_local_offst() -> timedelta:"""獲取當前時區相對UTC-0的偏移"""timestamp: float = time.time()local_datetime_obj: datetime = datetime.fromtimestamp(timestamp)utc0_datetime_obj: datetime = datetime.utcfromtimestamp(timestamp)offset: timedelta = local_datetime_obj - utc0_datetime_objreturn offsetdef seconds_to_left_str(input_seconds: float) -> str:"""秒數seconds轉剩余倒計時:XX時XX分XX秒https://www.runoob.com/python/att-string-format.html"""hours = 0minutes = 0seconds = 0input_seconds = int(input_seconds)if input_seconds >= 0:hours = int(input_seconds / HOUR_SECOND)minutes = int(input_seconds % HOUR_SECOND / MINUTE_SECOND)seconds = int(input_seconds % MINUTE_SECOND)# 例如:(100, 1, 10) ==> 100時01分10秒; (0, 0, 0) ==> 0時00分00秒return "{:0>d}時{:0>2d}分{:0>2d}秒".format(hours, minutes, seconds)if __name__ == "__main__":print(f'utc-0 time_str: {timestamp_to_utc_str(time.time())}')print(f'utc-local time_str: {timestamp_to_local_str(time.time())}')print(f'utc-0 time_str: {get_now_time_str(False, 0)}')print(f'utc-local time_str: {get_now_time_str()}')print(f'utc-local time_str:{get_local_date_str(time.time())}')print(f'utc-local offset:{get_local_offst()}')input_seconds = 6000print(f'{input_seconds} seconds==>{seconds_to_left_str(input_seconds)}')