1. 獲取時間
1.1. 時間戳
import time
timestamp = time.time()
# 1682737552.5009851
格林威治時間(GMT)1970年01月01日00時00分00秒起至現(xiàn)在的總秒數(shù)
1.2. 結(jié)構(gòu)化時間
import time
struct_time = time.localtime()
#time.struct_time(tm_year=2023, tm_mon=4, tm_mday=29, tm_hour=11, tm_min=6, tm_sec=43, tm_wday=6, tm_yday=120, tm_isdst=0)
1.3. 格式化時間
import time
format_time = time.strftime('%Y-%m-%d %H:%M:%S %p')
# 2023-04-29 11:07:30 AM
%Y Year with century as a decimal number.(年)
%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].(時-24時)
%M Minute as a decimal number [00,59].(分)
%S Second as a decimal number [00,61].(秒)
%z Time zone offset from UTC.(國際標(biāo)準(zhǔn)時間與本地時間(東八區(qū)北京時間)的時間差)
%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.(linux的時間格式)
%I Hour (12-hour clock) as a decimal number [01,12].(時-12時)
%p Locale’s equivalent of either AM or PM.(上午 or 下午)
%X 時:分:秒,與%H:%M:%S效果相同
%x 時/分/秒文章來源:http://www.zghlxwxcb.cn/news/detail-433043.html
2. 時間轉(zhuǎn)換
2.1. 時間戳 < > 結(jié)構(gòu)化時間
import time
timestamp = time.time()
# 1682738174.6577663
# 時間戳 > 結(jié)構(gòu)化時間
struct_time = time.localtime(timestamp) # 默認(rèn)time.time()
# time.struct_time(tm_year=2023, tm_mon=4, tm_mday=29, tm_hour=11, tm_min=16, tm_sec=14, tm_wday=6, tm_yday=120, tm_isdst=0)
# 結(jié)構(gòu)化時間 > 時間戳
timestamp = time.mktime(struct_time)
# 1682738174.0
2.2. 結(jié)構(gòu)化時間 < > 格式化時間
import time
struct_time = time.localtime()
#time.struct_time(tm_year=2023, tm_mon=4, tm_mday=29, tm_hour=11, tm_min=21, tm_sec=43, tm_wday=6, tm_yday=120, tm_isdst=0)
# 結(jié)構(gòu)化時間 > 格式化時間
format_time = time.strftime('%Y-%m-%d %H:%M:%S', struct_time)
#2023-04-29 11:21:43
# 格式化時間 > 結(jié)構(gòu)化時間
struct_time = time.strptime(format_time, '%Y-%m-%d %H:%M:%S')
#time.struct_time(tm_year=2023, tm_mon=4, tm_mday=29, tm_hour=11, tm_min=21, tm_sec=43, tm_wday=6, tm_yday=120, tm_isdst=-1)
謝謝文章來源地址http://www.zghlxwxcb.cn/news/detail-433043.html
到了這里,關(guān)于Python time模塊時間獲取和轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!