python基于给定时间戳生成 未来/过去 前进/倒退 n个小时的时间戳

      今天遇上一个需求就是,给定一个时间戳,需要得到倒退n个小时或者是前进n个小时后的时间戳,这个借助于datetime模块就可以完成了,我之前的博客里面就有相关的实现,这里整理出来完善一下:

#!usr/bin/env python
#encoding:utf-8


'''
__Author__:沂水寒城
功能:python基于给定时间戳生成 未来/过去  前进/倒退  n个小时的时间戳
'''


import datetime


def getBeforeTime(timestamp,hours,format='%Y-%m-%d %H:%M:%S'):
    '''
    以给定时间戳为基准,后退 hours 个小时得到对应的时间戳
    '''
    now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
    for i in range(hours):
        now_time-=datetime.timedelta(hours=1)
    next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
    print 'next_timestamp: ',next_timestamp
    return next_timestamp


def getFutureTime(timestamp,hours,format='%Y-%m-%d %H:%M:%S'):
    '''
    以给定时间戳为基准,前进 hours 个小时得到对应的时间戳
    '''
    now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
    for i in range(hours):
        now_time+=datetime.timedelta(hours=1)
    next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
    print 'next_timestamp: ',next_timestamp
    return next_timestamp


if __name__=='__main__':
    timestamp='2018-12-19 11:00:00'
    getBeforeTime(timestamp,15,format='%Y-%m-%d %H:%M:%S')
    print '-*'*40
    getFutureTime(timestamp,15,format='%Y-%m-%d %H:%M:%S')

        结果如下:

next_timestamp:  2018-12-18 20:00:00
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
next_timestamp:  2018-12-20 02:00:00

       datetime还是很强大的有木有!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Together_CZ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值