从日期时间到时间戳 python
From datetime to timestamp python
我需要将具有微秒分辨率的日期时间对象转换为时间戳,问题是我没有获得相同的时间戳秒分辨率。
例如,我作为参数传递的时间戳是 1424440192,我得到的是 return 1424429392.011750,这是为什么?我只更改了 datetime 对象的微秒值,所以我希望只更改值点之后。
PD:在这个例子中我只模拟了一个时间戳。
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
return td.total_seconds()
#return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
#10**6) / 1e6
timestamp_pc = 1424440192
tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)
print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))
我明白了。
我变了
tm = datetime.fromtimestamp(timestamp_pc)
为了
tm = datetime.utcfromtimestamp(timestamp_pc)
现在时间戳是一样的。
来自fromtimestamp
documentation:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
由于您的 totimestamp
函数不会反向进行相同的时区调整,因此您的时区偏移导致时间错误。
我需要将具有微秒分辨率的日期时间对象转换为时间戳,问题是我没有获得相同的时间戳秒分辨率。
例如,我作为参数传递的时间戳是 1424440192,我得到的是 return 1424429392.011750,这是为什么?我只更改了 datetime 对象的微秒值,所以我希望只更改值点之后。 PD:在这个例子中我只模拟了一个时间戳。
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
return td.total_seconds()
#return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
#10**6) / 1e6
timestamp_pc = 1424440192
tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)
print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))
我明白了。
我变了
tm = datetime.fromtimestamp(timestamp_pc)
为了
tm = datetime.utcfromtimestamp(timestamp_pc)
现在时间戳是一样的。
来自fromtimestamp
documentation:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
由于您的 totimestamp
函数不会反向进行相同的时区调整,因此您的时区偏移导致时间错误。