Python datetime 模块之时间取整,整秒、整分、整时、整天

____tz_zs

#!/usr/bin/python2.7
# -*- coding:utf-8 -*-

"""
@author:    tz_zs
"""
from datetime import datetime
from datetime import timedelta


def get_hourly_chime(dt, step=0, rounding_level="s"):
    """
    计算整分钟,整小时,整天的时间
    :param step: 往前或往后跳跃取整值,默认为0,即当前所在的时间,正数为往后,负数往前。
                例如:
                step = 0 时 2019-04-11 17:38:21.869993 取整秒后为 2019-04-11 17:38:21
                step = 1 时 2019-04-11 17:38:21.869993 取整秒后为 2019-04-11 17:38:22
                step = -1 时 2019-04-11 17:38:21.869993 取整秒后为 2019-04-11 17:38:20
    :param rounding_level: 字符串格式。
                "s": 按秒取整;"min": 按分钟取整;"hour": 按小时取整;"days": 按天取整
    :return: 整理后的时间戳
    """
    if rounding_level == "days":  # 整天
        td = timedelta(days=-step, seconds=dt.second, microseconds=dt.microsecond, milliseconds=0, minutes=dt.minute, hours=dt.hour, weeks=0)
        new_dt = dt - td
    elif rounding_level == "hour":  # 整小时
        td = timedelta(days=0, seconds=dt.second, microseconds=dt.microsecond, milliseconds=0, minutes=dt.minute, hours=-step, weeks=0)
        new_dt = dt - td
    elif rounding_level == "min":  # 整分钟
        td = timedelta(days=0, seconds=dt.second, microseconds=dt.microsecond, milliseconds=0, minutes=-step, hours=0, weeks=0)
        new_dt = dt - td
    elif rounding_level == "s":  # 整秒
        td = timedelta(days=0, seconds=-step, microseconds=dt.microsecond, milliseconds=0, minutes=0, hours=0, weeks=0)
        new_dt = dt - td
    else:
        new_dt = dt
    # timestamp = new_dt.timestamp()  # 对于 python 3 可以直接使用 timestamp 获取时间戳
    timestamp = (new_dt - datetime.fromtimestamp(0)).total_seconds()  # Python 2 需手动换算
    return timestamp
def dt_to_timestamp(dt):
	# timestamp = dt.timestamp()  # 对于 python 3 可以直接使用 timestamp 获取时间戳
	timestamp = (dt - datetime.fromtimestamp(0)).total_seconds()  # Python 2 需手动换算
	return timestamp
def get_now_timestamp():
	# 获取当前时间的 timestamp时间戳
	timestamp = (datetime.now() - datetime.fromtimestamp(0)).total_seconds()  #
	return timestamp

使用案例1

整点心跳功能

# 整点心跳功能
while 1# 做你自己的事
	time1 = get_now_timestamp()
	run1()
	run2()
	run3()
	... ...
	time2 = get_now_timestamp()
	
	# 每到整点打印一下,证明自己还活着。
	dt_now = datetime.now()
	timestamp = get_hourly_chime(dt=dt_now, step=1, rounding_level="hour") # 得到整点的时间戳
	now_timestamp = dt_to_timestamp(dt_now)  # 得到当前的时间戳
	
	if (timestamp - now_timestamp) < (time2 - time1):  # 判定时间。
	    time.sleep(timestamp - now_timestamp)
	    print("alive Hourly chime %s" % datetime.now().isoformat())

使用案例2

先获取当前的时间,使用 get_hourly_chime 函数,归整为分钟级。

datetime_now = datetime.now()
print(datetime_now)  # 2019-04-30 17:31:38.146630
print(dt_to_timestamp(datetime_now))  # 1556616698.14663

t = get_hourly_chime(dt=datetime_now, step=-1, rounding_level="min")
print(t)  # 1556616600.0
print(datetime.fromtimestamp(t))  # 2019-04-30 17:30:00

t2 = get_hourly_chime(dt=datetime_now, step=0, rounding_level="min")
print(t2)  # 1556616660.0
print(datetime.fromtimestamp(t2))  # 2019-04-30 17:31:00

t3 = get_hourly_chime(dt=datetime_now, step=1, rounding_level="min")
print(t3)  # 1556616720.0
print(datetime.fromtimestamp(t3))  # 2019-04-30 17:32:00

更多 datetime 模块的使用:https://blog.csdn.net/tz_zs/article/details/81672280

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值