从datetime到时间戳python
我需要将具有微秒分辨率的datetime对象转换为时间戳,问题是我没有获得与秒分辨率相同的时间戳 例如,我作为参数传递的时间戳是1424440192,我得到的返回值是1424429392.011750,这是为什么?我只更改了datetime对象的微秒值,所以我希望只更改点后的值。 PD:在这个例子中,我只模拟了一个时间戳从datetime到时间戳python,python,python-2.7,datetime,timestamp,Python,Python 2.7,Datetime,Timestamp,我需要将具有微秒分辨率的datetime对象转换为时间戳,问题是我没有获得与秒分辨率相同的时间戳 例如,我作为参数传递的时间戳是1424440192,我得到的返回值是1424429392.011750,这是为什么?我只更改了datetime对象的微秒值,所以我希望只更改点后的值。 PD:在这个例子中,我只模拟了一个时间戳 from datetime import datetime, timedelta def totimestamp(dt, epoch=datetime(1970,1,1)):
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\u pc)
对于
tm=datetime.utcfromtimestamp(timestamp\u pc)
现在时间戳是相同的 来自:
如果可选参数tz为None或未指定,则时间戳将转换为平台的本地日期和时间,并且返回的datetime对象为naive
由于您的
totimestamp
功能没有反向执行相同的时区调整,因此您的时区偏移导致时间错误。如果您将tm=datetime.fromtimestamp…
和new_tm=tm放在两行之间,那么打印totimestamp(tm)
会显示什么?相关: