Skip to main content
 首页 » 编程设计

python之获取给定日期的 gps 周数

2025年05月04日11lonelyxmas

我有以下 Pandas 系列,想获得该日期的 GPS 周数:

import pandas as pd 
from pandas import Timestamp 
times = pd.Series([Timestamp('2015-11-27 00:00:00.540000'), Timestamp('2015-11-27 00:00:00.699000'), Timestamp('2015-11-27 00:00:01'), Timestamp('2015-11-27 00:00:01.699000'), Timestamp('2015-11-27 00:00:02.699000')]) 
 
In [116]: times 
Out[116]: 
0   2015-11-27 00:00:00.540 
1   2015-11-27 00:00:00.699 
2   2015-11-27 00:00:01.000 
3   2015-11-27 00:00:01.699 
4   2015-11-27 00:00:02.699 
Name: GMT, dtype: datetime64[ns] 

当我尝试减去 GPS 纪元开始的日期并获得总秒数时:

gps_epoch = datetime.datetime(1980, 1, 6) 
delta = times - gps_epoch 
 
In [120]: delta 
Out[120]: 
0   13109 days 00:00:00.540000 
1   13109 days 00:00:00.699000 
2          13109 days 00:00:01 
3   13109 days 00:00:01.699000 
4   13109 days 00:00:02.699000 
Name: GMT, dtype: timedelta64[ns] 

我正在尝试为该系列映射 total_seconds 但是我遇到了一个错误:

In [124]: delta.map(lambda x: x.total_seconds()) 
AttributeError: 'numpy.timedelta64' object has no attribute 'total_seconds' 

但是当我试图获取第一个元素的总秒数时,一切都很好:

In [130]: delta[0].total_seconds() 
Out[130]: 1132617600.54 

然后为了获得 GPS 周数,我可以执行以下操作:

In [135]: np.floor(delta[0].total_seconds()/86400/7) 
Out[135]: 1872.0 

我已经检查了这两种情况的类型,它们是不同的..:

In [137]: type(delta[0]) 
Out[137]: pandas.tslib.Timedelta 
 
In [138]: delta.map(lambda x: type(x)) 
Out[138]: 
0    <class 'numpy.timedelta64'> 
1    <class 'numpy.timedelta64'> 
2    <class 'numpy.timedelta64'> 
3    <class 'numpy.timedelta64'> 
4    <class 'numpy.timedelta64'> 
Name: GMT, dtype: object 

问题是为什么它不能使用 map 方法以及为什么类型不同?

请您参考如下方法:

你可以做 dt.total_seconds :

In [67]: 
delta.dt.total_seconds() 
 
Out[67]: 
0    1.132618e+09 
1    1.132618e+09 
2    1.132618e+09 
3    1.132618e+09 
4    1.132618e+09 
dtype: float64 

和:

In [68]: 
np.floor(delta.dt.total_seconds()/86400/7) 
 
Out[68]: 
0    1872 
1    1872 
2    1872 
3    1872 
4    1872 
dtype: float64 

或者使用floordiv:

In [84]: 
delta.dt.total_seconds().floordiv(86400).floordiv(7) 
 
Out[84]: 
0    1872 
1    1872 
2    1872 
3    1872 
4    1872 
dtype: float64 

发生错误是因为 dtype 被转换为 np.timedelta 没有 totalseconds 属性,而 pandas timedelta 确实(因为它是 datetime.timedelta 的子类)参见:http://pandas.pydata.org/pandas-docs/stable/timedeltas.html

考虑以下几点:

In [97]: 
type(delta[0]) 
 
Out[97]: 
pandas.tslib.Timedelta 
 
In [100]:     
delta[[0]].map(lambda x: print(type(x))) 
 
<class 'numpy.timedelta64'> 
Out[100]: 
0    None 
dtype: object 

这可能是为了提供与 np 方法的兼容性,但您可以使用 dt.totalseconds 作为方便的例程