如何按年份扩展熊猫时间戳?

时间:2018-07-13 01:20:56

标签: python pandas numpy

我有一个约会:

birth_day = pd.to_datetime('1984-09-03')

,我正在尝试创建一系列日期,每年重复一次。这是我尝试过的:

birth_days = birth_day + pd.to_timedelta(np.arange(10), 'Y')

输出与我期望的不完全相同。生成的日期具有不同的小时信息:

DatetimeIndex(['1984-09-03 00:00:00', '1985-09-03 05:49:12',
               '1986-09-03 11:38:24', '1987-09-03 17:27:36',
               '1988-09-02 23:16:48', '1989-09-03 05:06:00',
               '1990-09-03 10:55:12', '1991-09-03 16:44:24',
               '1992-09-02 22:33:36', '1993-09-03 04:22:48'],
              dtype='datetime64[ns]', freq=None)

如何在所有时间为00:00:00的地方创建此列表?

1 个答案:

答案 0 :(得分:3)

您可以尝试DateOffset

[birth_day-pd.DateOffset(years=x) for x in np.arange(10)]
Out[87]: 
[Timestamp('1984-09-03 00:00:00'),
 Timestamp('1983-09-03 00:00:00'),
 Timestamp('1982-09-03 00:00:00'),
 Timestamp('1981-09-03 00:00:00'),
 Timestamp('1980-09-03 00:00:00'),
 Timestamp('1979-09-03 00:00:00'),
 Timestamp('1978-09-03 00:00:00'),
 Timestamp('1977-09-03 00:00:00'),
 Timestamp('1976-09-03 00:00:00'),
 Timestamp('1975-09-03 00:00:00')]