代码之家  ›  专栏  ›  技术社区  ›  bwrr

将两个时间戳浮动转换为可读的年、月和日数

  •  0
  • bwrr  · 技术社区  · 7 年前

    tms1 = 1479081600.0
    tms2 = 1482105600.0
    

    在计算差异时,我得到

    tms2 - tms1
    3024000.0
    

    (答案是2016年11月14日至2016年12月19日之间的35天,使用在线unix时差计算器)

    2 回复  |  直到 7 年前
        1
  •  5
  •   Izaak van Dongen Andy Hubbard    7 年前

    import 惯性导航与制导 datetime )

    datetime.timedelta(seconds=3024000).days
    

    35
    

    timedelta 因为这是一个时间差-一个时间差,而不是绝对时间。也可以通过强制 时间增量

    print(datetime.timedelta(seconds=3024000))
    

    给出输出:

    35 days, 0:00:00
    

    注意,你不需要任何在线计算器- 附带电池。你可以做:

    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 这里与原件相同 时间增量 日期时间 而不是静态构造。我还演示了一个事实,如果您愿意的话,您可以从时间戳构建日期时间,我还冒昧地演示了 strftime 日期时间 方法优于算术方法,因为它更具可读性和可扩展性。

    这个答案相当轻量级,这并不一定是坏事,因为通常你可能不需要比它提供更多的功能,但如果 时间增量 the legendary Raymond's awesome answer

        2
  •  1
  •   Raymond Hettinger    7 年前

    仅仅减去秒并不能帮助您知道是否已经跨越了一天的边界,因此有必要将时间戳转换为 datetime

    添加由于时区可能会影响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