赞
踩
经常遇到处理时间与获取当前时间,之前记录了一版Scala版本的,现在记录一下Python版本的:
Tip: 导入类
- import time
- import datetime
1.获取当前时间
- now = datetime.datetime.now()
- print now
- print now.year
- print now.month
- print now.day
- print now.hour
- print now.minute
- print now.second
- print now.microsecond
2.获取指定时间
这里的 format = '%Y%m%d' 需要根据自己的时间格式进行自定义修改。
- startdate = datetime.datetime.strptime(startdate, '%Y%m%d')
- print startdate.year
- print startdate.month
- print startdate.day
- print startdate.hour
- print startdate.minute
- print startdate.second
- print startdate.microsecond
1.获取当前时间时间戳
- t = time.time()
- #秒级:
- print int(t)
- #毫秒级:
- print int(round(t * 1000))
- #微秒级:
- print int(round(t * 1000000))
2.获取指定时间时间戳
这里同样需要注意对应的 format 格式
- t = '20210101'
- t = int(time.mktime(time.strptime(t,"%Y%m%d")))
- #秒级:
- print int(t)
- #毫秒级:
- print int(round(t * 1000))
- #微秒级:
- print int(round(t * 1000000))
通过时间偏移量 datetime.timedelta() 决定要增减的时间,然后 +/- 即可,下面使用了两种模式,都可以达到目的。
- # 获取时间
- now = datetime.datetime.now()
- # 时间增加
- now_plus_one_day = now + datetime.timedelta(days=+1)
- # 时间减小
- now_sub_five_minute = now - datetime.timedelta(days=0, hours=0, minutes=5, seconds=00)
- gap = 0
- while startdate <= enddate:
- gap += 1
- print startdate
- startdate += datetime.timedelta(days=+1)
- print "相差" + str(gap) + "天"
结果:
- 2020-12-24 00:00:00
- 2020-12-25 00:00:00
- 2020-12-26 00:00:00
- 2020-12-27 00:00:00
- 2020-12-28 00:00:00
- 2020-12-29 00:00:00
- 2020-12-30 00:00:00
- 2020-12-31 00:00:00
- 2021-01-01 00:00:00
- 2021-01-02 00:00:00
- 2021-01-03 00:00:00
- 相差11天
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。