簡體   English   中英

在python中直到一天結束的秒數

[英]Seconds until end of day in python

還有另外一個問題, 在這里,詢問多少秒,因為午夜-這個問題是相反的。

如何使用 python 從當前時間獲取到一天結束的秒數?

我找到的最干凈的方法是

def time_until_end_of_day(dt=None):
    # type: (datetime.datetime) -> datetime.timedelta
    """
    Get timedelta until end of day on the datetime passed, or current time.
    """
    if dt is None:
        dt = datetime.datetime.now()
    tomorrow = dt + datetime.timedelta(days=1)
    return datetime.datetime.combine(tomorrow, datetime.time.min) - dt

取自http://wontonst.blogspot.com/2017/08/time-until-end-of-day-in-python.html

然而,這不是最快的解決方案 - 您可以運行自己的計算以獲得加速

def time_until_end_of_day(dt=None):
    if df is None:
        dt = datetime.datetime.now()
    return ((24 - dt.hour - 1) * 60 * 60) + ((60 - dt.minute - 1) * 60) + (60 - dt.second)

時間結果:

慢:3.55844402313 快:1.74721097946(103% 加速)

正如 Jim Lewis 所指出的,在這種情況下,這種更快的功能會在夏令時開始/停止時中斷。

from datetime import datetime
from datetime import timedelta

def seconds_until_end_of_today():
    time_delta = datetime.combine(
        datetime.now().date() + timedelta(days=1), datetime.strptime("0000", "%H%M").time()
    ) - datetime.now()
    return time_delta.seconds

到一天結束的秒數是一天中總秒數與從一天開始經過的秒數之差:

import datetime
seconds_in_a_day = 86400  # the number of seconds in one day
dt = datetime.datetime.now()
midnight = datetime.datetime.combine(dt.date(), datetime.time())  # current date with zero time (00:00:00)
seconds_since_midnight = (dt - midnight).seconds  # the number of seconds since the beginning of the day
seconds_until_end_of_day = seconds_in_a_day - seconds_since_midnight  # the number of seconds remaining until the end of the day

您可以同時使用 DateTime 和 timedelta 來計算距離午夜還剩多少秒。

from datetime import timedelta, datetime


def seconds_till_midnight(current_time):
    """
    :param current_time: Datetime.datetime 
    :return time till midnight in seconds: 
    """
    # Add 1 day to the current datetime, which will give us some time tomorrow
    # Now set all the time values of tomorrow's datetime value to zero, 
    # which gives us midnight tonight
    midnight = (current_time + timedelta(days=1)).replace(hour=0, minute=0, microsecond=0, second=0)
    # Subtracting 2 datetime values returns a timedelta
    # now we can return the total amount of seconds till midnight
    return (midnight - current_time).seconds


if __name__ == '__main':
    now = datetime.now()
    seconds_left_in_the_day = seconds_till_midnight(now)
    print(seconds_left_in_the_day)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM