您可以保留精度,因为在 Python 中时间戳是一个浮点数。这是一个例子:
import datetime
java_timestamp = 1241959948938
seconds = java_timestamp / 1000
sub_seconds = (java_timestamp % 1000.0) / 1000.0
date = datetime.datetime.fromtimestamp(seconds + sub_seconds)
你显然可以让它比这更紧凑,但上面的代码适合在 REPL 中一次一行地输入,所以看看它做了什么。例如:
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> java_timestamp = 1241959948938
>>> import datetime
>>> seconds = java_timestamp / 1000
>>> seconds
1241959948L
>>> sub_seconds = (java_timestamp % 1000.0) / 1000.0
>>> sub_seconds
0.93799999999999994
>>> date = datetime.datetime.fromtimestamp(seconds + sub_seconds)
>>> date
datetime.datetime(2009, 5, 10, 8, 52, 28, 938000)
>>>