2015-02-23 187 views
1

我需要将微秒分辨率的日期时间对象转换为时间戳,问题是我没有得到相同的时间戳秒的分辨率。从日期时间到时间戳python

例如,我作为参数传递的时间戳是1424440192,而我得到的返回值为1424429392.011750,为什么这样呢?I只更改了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)) 
+0

如果您将'tm = datetime.fromtimestamp ...'和'new_tm = tm.replace ...'放在行之间,那么'print totimestamp(tm)'会显示什么? – BorrajaX 2015-02-23 19:32:05

+0

相关:[在Python中将datetime.date转换为UTC时间戳](http://stackoverflow.com/q/8777753/4279) – jfs 2015-02-24 04:58:34

回答

0

fromtimestamp documentation

如果可选参数TZ是无或不指定,时间戳转换为平台的本地日期和时间,返回的DateTime对象是幼稚的。

由于您的totimestamp函数不能在相反的时间域进行相同的调整,因此您的时区偏移会导致时间错误。

2

我明白了。 我改变 tm = datetime.fromtimestamp(timestamp_pc)tm = datetime.utcfromtimestamp(timestamp_pc)

现在时间戳是相同的。