【问题标题】:Python timedelta error: skipping a day when trying to get tomorrowPython timedelta错误:尝试获取明天时跳过一天
【发布时间】:2016-08-22 15:53:33
【问题描述】:

我有以下代码:

import time
from datetime import date, datetime, timedelta


def getNextDay(last_day):
    #Returns tomorrows timestamp at two times: 00:00 and 23:59
    last_day = datetime.utcfromtimestamp(last_day)
    tomorrow = last_day + timedelta(days=1)
    tomorrow_start = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 0, 0, 0, 0)
    tomorrow_end = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 23, 59, 0, 0)
    return [time.ctime(int(tomorrow_start.strftime("%s"))), time.ctime(int(tomorrow_end.strftime("%s")))]


last_day = 1370054073 #unix-timestamp

print "The day is:"
print time.ctime(last_day)

print "The next day is:"
print getNextDay(last_day)

当我运行它时,输出是:

The day is:
Fri May 31 23:34:33 2013
The next day is:
['Sun Jun  2 00:00:00 2013', 'Sun Jun  2 23:59:00 2013']

我找不到问题所在,因为 getNextDay() 函数似乎是正确的:我想在 00:00 和 23:59 从 1370054073 获取明天。但是它跳过了一天,第二天的输出应该是['Sat Jun 1 00:00:00 2013', 'Sat Jun 1 23:59:00 2013']

谁能告诉我哪里做错了?

【问题讨论】:

    标签: python timestamp unix-timestamp timedelta


    【解决方案1】:

    来自time.ctime的文档:

    将自纪元以来以秒表示的时间转换为表示本地时间的字符串。如果未提供secsNone,则使用time() 返回的当前时间。 ctime(secs) 等价于 asctime(localtime(secs))ctime() 不使用区域信息。

    因此,当您使用 print time.ctime(last_day) 时,您会看到基于您的当地时间的时间:

    Fri May 31 23:34:33 2013
    

    但是,当我使用它时,我看到了不同的时间:

    Sat Jun  1 08:04:33 2013
    

    您可以获得实际的UTC时间如下:

    >>> datetime.utcfromtimestamp(last_day)
    datetime.datetime(2013, 6, 1, 2, 34, 33)
    

    而且,正如您所见,它已经是 June 1,因此您的功能正常工作,并且没有跳过任何日子。

    【讨论】:

    • 这很奇怪,我在在线服务器(http://goo.gl/hz2KUS)上测试过,你是对的。谢谢你,@AKS
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2016-08-08
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多