Python 获取时间,时间戳,时间差

经常遇到处理时间与获取当前时间,之前记录了一版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天

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BIT_666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值