python的time 模块常用的与时间相关的类和函数

1.1 struct_time 类
time 模块的 struct_time 类代表一个时间对象,可以通过索引和属性名访问值。 对应关系如下:

索引 对应相对的属性值,常用的索引就年,月,日,时,分
0 —— tm_year(年) 如:1945
1 —— tm_mon(月) 1 ~ 12
2 —— tm_mday(日) 1 ~ 31
3 —— tm_hour(时) 0 ~ 23
4 —— tm_min(分) 0 ~ 59
5 —— tm_sec(秒) 0 ~ 60
6 —— tm_wday(周) 0 ~ 6
7 —— tm_yday(一年内第几天) 1 ~ 366
8 —— tm_isdst(夏时令) -1、0、1
localtime() 表示当前时间,返回类型为 struct_time 对象,

import time
t = time.localtime()              #实例化当前时间
print('t-->', t)                #当前时间数据
print('tm_year-->', t.tm_year)          #当前年份
print('tm_year-->', t[1])              #数组中的时间索引 年 月 日索引  从0开始

1.2常用函数用法
time()——返回当前时间的时间戳
gmtime([secs])——将时间戳转换为格林威治天文时间下的 struct_time,可选参数 secs 表示从 epoch 到现在的秒数,默认为当前时间
localtime([secs])——与 gmtime() 相似,返回当地时间下的 struct_time
mktime(t) localtime() 的反函数
asctime([t]) 接收一个 struct_time 表示的时间,返回形式为:Mon Dec 2 08:53:47 2019 的字符串
ctime([secs]) ctime(secs) 相当于 asctime(localtime(secs))
strftime(format[, t]) 格式化日期,接收一个 struct_time 表示的时间,并返回以可读字符串表示的当地时间
sleep(secs) 暂停执行调用线程指定的秒数
altzone 本地 DST 时区的偏移量,以 UTC 为单位的秒数
timezone 本地(非 DST)时区的偏移量,UTC 以西的秒数(西欧大部分地区为负,美国为正,英国为零)
tzname 两个字符串的元组:第一个是本地非 DST 时区的名称,第二个是本地 DST 时区的名称

import time

print(time.gmtime())
print(time.localtime())
print(time.asctime(time.localtime()))
print(time.tzname)
# strftime 使用
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

strftime 函数日期格式化符号说明如图所示:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值