Python时间增量错误: skipping a day when trying to get tomorrow

标签 python timestamp unix-timestamp timedelta

我有以下代码:

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() 函数似乎是正确的:我想从 1370054073 获取明天的 00:00 和 23:59。但它跳过一天,第二天的输出应该是 ['Sat Jun 1 00:00:00 2013', 'Sat Jun 1 23:59:00 2013']

有人可以告诉我哪里做错了吗?

最佳答案

来自 time.ctime 的文档:

Convert a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by 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)

而且,正如您所看到的,现在已经是 6 月 1 日,因此您的函数运行正常,并且不会跳过任何天。

关于Python时间增量错误: skipping a day when trying to get tomorrow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905256/

相关文章:

来自时间戳的java日期和时间

Android:数据库中的时间戳

mysql - MySQL 中 UNIX_TIMESTAMP 和 NOW() 的区别

actionscript-3 - AS3时间戳不正确

python - Python 中 Twitter API 的无效 JSON 对象

python - 绘制一个看起来像球体的球体

2038-01-19 之后的 MySQL from_unixtime?

mysql unix_timestamp 时区时间错误

python - 将包含字符串的 Pandas 系列转换为 boolean 值

python - 抑制 Python/unittest 的所有输出