【发布时间】:2015-12-12 02:06:51
【问题描述】:
我面临一个非常奇怪的问题。我有一个月中某一天的 UTC 时间戳,我需要找到月初和月底的 UTC 时间戳。
例如,如果时间戳 = 2015 年 1 月 7 日晚上 11 点的时间戳 = 1435791600 我需要时间戳一 2015 年 1 月 1 日上午 12 点和 1 月 31 日晚上 11:59。
问题是当我使用 datetime 计算一个月的第一天和最后一天,然后尝试从新值中检索时间戳时,时间戳是在本地时间返回的。
这是我的代码:
gb_timestamp = 1441065600000
print '------'
timestamp = datetime.datetime.utcfromtimestamp(gb_timestamp/1000.0)
print timestamp
print int(timestamp.strftime("%s")) * 1000
tsMonthStart = timestamp.replace(day=1).replace(hour=0).replace(minute=0).replace(second=0).replace(microsecond=0)
tsMonthEnd = timestamp.replace(hour=23).replace(minute=59).replace(second=59).replace(microsecond=999999)
mlist = [1,3,5,7,8,10,12]
if tsMonthEnd.month in mlist:
tsMonthEnd = tsMonthEnd.replace(day=31)
elif (tsMonthEnd.month == 2) and (tsMonthEnd.year%4 !=0):
tsMonthEnd = tsMonthEnd.replace(day=28)
elif (tsMonthEnd.month == 2) and (tsMonthEnd.year%4 ==0):
tsMonthEnd = tsMonthEnd.replace(day=29)
else:
tsMonthEnd = tsMonthEnd.replace(day=30)
print tsMonthStart
print tsMonthEnd
第一个打印语句将时间更改为 1441080000000。输出:
----------------
1441080000000
有人可以帮忙吗?我该如何解决这个问题。提前致谢。
【问题讨论】:
-
你可以清理你问题中的代码吗?这里的格式化文档应该会有所帮助:stackoverflow.com/help/formatting
-
不相关:使用
calendar.monthrange()查找该月的最后一天。使用utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=1441065600000)(假设输入是 POSIX 时间戳)而不是utcfromtimestamp(),以在某些平台上扩展范围并避免丢失浮点运算的精度。
标签: python python-2.7 datetime utc