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

你可能感兴趣的:(#,综合)