Python时间差错误:尝试获取tom时跳过一天

2024-04-29 02:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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']

有人能告诉我哪里做错了吗?你知道吗


Tags: theimportdatetimetimeisstarttimestampjun
1条回答
网友
1楼 · 发布于 2024-04-29 02:17:30

来自^{}的文档:

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)

而且,如您所见,它已经June 1,因此您的函数工作正常,不会跳过任何一天。你知道吗

相关问题 更多 >