簡體   English   中英

將兩個時間戳浮點轉換為可讀的年,月和日

[英]Convert two timestamp floats to a readable number of years, months, and days

我有兩個以浮點格式存儲的時間戳:

tms1 = 1479081600.0
tms2 = 1482105600.0

通過計算差異,我得到

tms2 - tms1
3024000.0

如何以天,月或年為單位,以可讀取的格式顯示3024000的時差? (答案是從2016年11月14日到2016年12月19日之間的35天,使用的是在線Unix時差計算器)

您可以使用(在import datetime

datetime.timedelta(seconds=3024000).days

這是

35

您應該使用timedelta因為這是時間增量-時間差,而不是絕對時間。 也可以通過將timedelta為字符串來獲得完整的表示形式:

print(datetime.timedelta(seconds=3024000))

給出輸出:

35 days, 0:00:00

請注意,您不需要任何在線計算器, datetime隨附電池。 您可以這樣做:

import datetime

date_format = "%d %b %Y"

start_date = datetime.datetime.strptime("14 Nov 2016", date_format)
end_date = datetime.datetime.strptime("19 Dec 2016", date_format)

print(start_date == datetime.datetime.fromtimestamp(1479081600))

print(start_date)
print(end_date.strftime("%d/%m/%Y"))

diff = end_date - start_date

print(diff)
print(diff.days)

輸出:

True
2016-11-14 00:00:00
19/12/2016
35 days, 0:00:00
35

請注意,此處的diff與原始timedelta對象相同,但是從datetime s動態創建,而不是靜態構造。 我還演示了一個事實,您可以根據需要從時間戳構建日期時間,並且我還自由地演示了strftime等來說明日期時間的功能。 我強烈建議使用datetime方法而不是算術方法,因為它更具可讀性和可擴展性。

這個答案是非常輕量級的,並不一定很糟糕,因為通常您可能不需要提供比其提供的功能更多的功能,但是,如果timedelta之間的timedelta間隔少於24小時,則它將舍入為0天。 它也不能處理時區。 如果您需要其中任何一個,請參見傳說中的雷蒙德出色的答案

僅減去秒並不能幫助您了解是否已超出日期邊界,因此在計算日期之前必須將時間戳轉換為日期時間對象。

另外,由於時區會影響UTC時間戳的日歷天,因此您可能還需要tzinfo對象。

一旦知道日歷日期,就需要一些日歷數學來計算年,月和日的差異:

from datetime import timedelta, datetime

def time_diff(start_timestamp, end_timestamp, tz=None):
    """ Return time difference in years, months, and days.

        If *tz* is None, the timestamp is converted to the platform’s local date 
        and time.  Otherwise, *tz* should be an instance of a *tzinfo* subclass.
    """

    # Determine whether we're going forward or backward in time
    ago = ''
    if end_timestamp < start_timestamp:
        ago = 'ago'
        start_timestamp, end_timestamp = end_timestamp, start_timestamp

    # Compute the calendar dates from the timestamps
    d1  = datetime.fromtimestamp(start_timestamp, tz)
    d2  = datetime.fromtimestamp(end_timestamp, tz)

    # Advance d1 day-by-day until the day is at or above d2.day
    days = 0
    while d2.day < d1.day:
        days += 1
        d1 += timedelta(days=1)

    # Now compute the day difference
    days += d2.day - d1.day

    # Compute the totals months difference and express in years and months
    total_months = (d2.year * 12 + d2.month) - (d1.year * 12 + d1.month)
    years, months = divmod(total_months, 12)

    # format the output
    plural = lambda n: '' if n == 1 else 's'
    return '%d year%s, %d month%s, and %d day%s %s' % (
        years, plural(years), months, plural(months), days, plural(days), ago)

這是如何使用該函數的示例:

from datetime import tzinfo

class GMT1(tzinfo):
    # Example tzinfo subclass taken from the Python docs
    def utcoffset(self, dt):
        return timedelta(hours=1)
    def dst(self, dt):
        return timedelta(0)
    def tzname(self,dt):
        return "Europe/Prague"

print(time_diff(1479081600.0, 1482105600.0, tz=GMT1()))

輸出:

0 years, 1 month, and 5 days

暫無
暫無

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

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