1. 获取时间
1.1. 时间戳
import time
timestamp = time.time()
# 1682737552.5009851
格林威治时间(GMT)1970年01月01日00时00分00秒起至现在的总秒数
1.2. 结构化时间
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.(国际标准时间与本地时间(东八区北京时间)的时间差)
%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 时/分/秒文章来源:https://www.toymoban.com/news/detail-433043.html
2. 时间转换
2.1. 时间戳 < > 结构化时间
import time
timestamp = time.time()
# 1682738174.6577663
# 时间戳 > 结构化时间
struct_time = time.localtime(timestamp) # 默认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)
# 结构化时间 > 时间戳
timestamp = time.mktime(struct_time)
# 1682738174.0
2.2. 结构化时间 < > 格式化时间
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)
# 结构化时间 > 格式化时间
format_time = time.strftime('%Y-%m-%d %H:%M:%S', struct_time)
#2023-04-29 11:21:43
# 格式化时间 > 结构化时间
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)
谢谢文章来源地址https://www.toymoban.com/news/detail-433043.html
到了这里,关于Python time模块时间获取和转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!