python 中的 UTC 时间戳正在转换为本地
UTC timestamp in python getting converted local
我遇到了一个很奇怪的问题。我有一个月中某一天的 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
有人可以帮忙吗。我应该如何解决这个问题。提前致谢。
这不是将 datetime
s 转换回 unix 时间戳的方式。使用这样的东西:
def datetime_to_timestamp(dt):
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
答案 here 解释了为什么 strftime('%s')
对 datetime
个对象无效。
我遇到了一个很奇怪的问题。我有一个月中某一天的 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
有人可以帮忙吗。我应该如何解决这个问题。提前致谢。
这不是将 datetime
s 转换回 unix 时间戳的方式。使用这样的东西:
def datetime_to_timestamp(dt):
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
答案 here 解释了为什么 strftime('%s')
对 datetime
个对象无效。