Skip to main content
 首页 » 编程设计

python之为什么从 np.datetime64 到 float 和 back 的转换会导致时差

2025年05月04日15daizhj

使用以下代码,我在转换回 np.datetime64 后得到两个小时的差异。

我怎样才能避免这种情况? (如果这应该是一个话题:我目前在中欧)

import pandas as pd 
import numpy as np 
import datetime 
 
a = np.datetime64('2018-04-01T15:30:00').astype("float") 
a 
b = np.datetime64(datetime.datetime.fromtimestamp(a)) 
b 
 
Out[18]: numpy.datetime64('2018-04-01T17:30:00.000000') 

请您参考如下方法:

问题不在 np.datetime64 转换中,而在 datetime.datetime.fromtimestamp 中。

Since Numpy 1.11 , np.datetime64 是天真的时区。它不再假设输入是本地时间,也不再打印本地时间。

但是,datetime.datetime.fromtimestamp 确实采用本地时间。来自docs :

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). 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.

您可以使用 datetime.datetime.utcfromtimestamp相反:

>>> a = np.datetime64('2018-04-01T15:30:00').astype("float") 
>>> np.datetime64(datetime.datetime.utcfromtimestamp(a)) 
numpy.datetime64('2018-04-01T15:30:00.000000')