python随机时间运行_Python—时间模块(time)和随机模块(random)

时间模块

time模块

获取秒级时间戳、毫秒级时间戳、微秒级时间戳

import time

t = time.time()

print t # 原始时间数据 1574502460.90

print int(t) # 秒级时间戳:10位 1574502460

print int(round(t * 1000)) # 毫秒级时间戳:13位 1574502460904

print int(round(t * 1000000)) # 微秒级时间戳:16位 1574502460903997

格式化日期与秒级时间戳之间的转换

import time

# 将日期转为秒级时间戳

dt = '2019-08-08 10:00:00'

ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))

print ts # 结果:1565229600

# 将秒级时间戳转为日期

ts = 1565229600

dt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts))

print dt # 结果:2019-08-08 10:00:00

# 将当前秒级时间戳转为日期,下面两种写法的结果是一样的

ct = time.strftime('%Y-%m-%d %H:%M:%S')

ct = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

print ct, type(ct) # 结果:2019-11-25 09:45:09

转结构体时间struct_time

# 日期时间转结构体

ta_dt = time.strptime("2019-11-25 10:20:50", '%Y-%m-%d %H:%M:%S')

print ta_dt # time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=10, tm_min=20, tm_sec=50, tm_wday=0, tm_yday=329, tm_isdst=-1)

# 时间戳转结构体,注意时间戳要求为int,也可以不带参数:ta_ms = time.localtime()

ta_ms = time.localtime(1574648450)

print ta_ms # time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=10, tm_min=20, tm_sec=50, tm_wday=0, tm_yday=329, tm_isdst=0)

print ta_ms[0], ta_ms[1], ta_ms[2], ta_ms[3], ta_ms[4], ta_ms[5]

其他用法

print time.time() # 结果:1574655005.15,现在距离计算机元年过去了多少秒。

print time.ctime() # 结果:Mon Nov 25 12:10:05 2019

print time.sleep(3) # 结果:程序运行到这儿,暂停3秒,休眠3秒。

print time.asctime((2019,5,7,20,8,8,6,3,1)) # 结果:Sun May 7 20:08:08 2019

print time.mktime((2019,5,9,20,8,8,0,0,0)) # 结果:1557403688.0

print time.gmtime(7200) # 结果:time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

print time.gmtime(1557403688) # 结果:time.struct_time(tm_year=2019, tm_mon=5, tm_mday=9, tm_hour=12, tm_min=8, tm_sec=8, tm_wday=3, tm_yday=129, tm_isdst=0)

print time.localtime(1557403688.0) # 结果:time.struct_time(tm_year=2019, tm_mon=5, tm_mday=9, tm_hour=20, tm_min=8, tm_sec=8, tm_wday=3, tm_yday=129, tm_isdst=0)

print time.localtime() # 结果:time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=12, tm_min=10, tm_sec=8, tm_wday=0, tm_yday=329, tm_isdst=0)

datetime模块

dateutil模块

from dateutil.parser import parse

t1 = parse('2019-10-01 10:10:10')

t2 = parse('2019-10-01/10:10:10')

t3 = parse('2019/12/01 10:10:10')

t4 = parse('2019/12/01/10:10:10')

print t1, type(t1) # 2019-10-01 10:10:10

print t2, type(t2) # 2019-10-01 10:10:10

print t3, type(t3) # 2019-12-01 10:10:10

print (t3-t1).days # 61

print (t3-t1).seconds # 0

print (t3-t1).total_seconds() # 5270400.0

随机模块

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值