time模块(时间模块)

时间模块
导入时间模块>>> import time
三种表达时间的方式 1,时间戳 2,格式化 3,对象数据结构
时间戳表达方式 例: 1533720874.982
格式化表达方式 例: 2018-08-08
对象数据结构 例: time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=15, tm_min=21, tm_sec=40, tm_wday=2, tm_yday=220, tm_isdst=0


时间模块常用元素

 
 



时间模块的三种取值方式
1,时间戳
import time
c=time.time()
print(c)          #时间戳(此时此刻的时间戳)
print(time.time())      #时间戳(此时此刻的时间戳)

2,格式化

import time
print(time.strftime('%Y-%m-%d'))    #格式化时间   结果格式:2018-08-08
print(time.strftime('%Y-%m-%d %H:%M:%S'))       #格式化的年月日时分秒

3,对象数据结构

import time
time_obj=time.localtime()       #对象数据结构    结果格式:time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=15, tm_min=21, tm_sec=40, tm_wday=2, tm_yday=220, tm_isdst=0)
print(time_obj)
print(time_obj.tm_year)         #想要拿到值,需要具体再取     结果:2018

 

 

集中模式之间的相互转换

 

例:

1,计算本月一号时间戳
import time
struct_time = time.localtime()      #先拿到对象数据结构
struct_time = time.strptime('%s-%s-1'%(struct_time.tm_year,struct_time.tm_mon),'%Y-%m-%d')
#上面这一行time.strptime结构,然后用格式化的方式改变了对象数据结构里的日(1),也可以改变年月
print(time.mktime(struct_time))     #再通过time.mktime将其转化成时间戳格式,此时读的就是改变之后的日期的时间戳
#结果:1533052800.0

2,拿到本月一号时间戳的另一种写法

ret=time.strftime('%Y-%m-1')    #先格式化时间拿到想要的日期
print(ret)
struct_time=time.strptime(ret,'%Y-%m-%d')   #将其转化成对象数据结构
print(struct_time)
print(time.mktime(struct_time))     #最后用time.mktime拿到时间戳

3,拿到我想要的日期

st=time.localtime()         #拿到对象数据结构
ko=time.strptime('%s-7-7' %(st.tm_year),'%Y-%m-%d')     #将其改成我需要的日期
lk=time.localtime(time.mktime(ko))      #(time.mktime(ko))得到我需要的时间戳,time.localtime将时间戳转化成对象数据类型
print(lk.tm_year,lk.tm_mon,lk.tm_mday)      #再从对象数据结构中把年月日拿出来

 

转载于:https://www.cnblogs.com/hdy19951010/p/9444304.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值