如何从日期时间列表中获取平均月份和日期?

How do I get the average month and day from a list of date times?

我有以下日期时间列表:

date_list = [Timestamp('2015-05-17 00:00:00'), Timestamp('2016-04-28 00:00:00'), Timestamp('2017-05-17 00:00:00'), Timestamp('2018-05-09 00:00:00'), Timestamp('2019-06-04 00:00:00'), Timestamp('2020-04-28 00:00:00')]

如何从此列表中获取平均日期和月份?我目前的代码如下:

avg_month_day = datetime.strftime(datetime.fromtimestamp(sum(map(datetime.timestamp,date_list))/len(date_list)),"%m-%d")

但是,加上年份,上面代码的结果是“11-10”,而我认为应该是“05-12”。

你得到这个平均值是因为考虑到了年份。您需要构造具有相同年份的新时间戳才能获得您想要的结果。

可能有更优雅的解决方案,但这里有一个应该可以正常工作的解决方案:

import pandas as pd

pd.Series(date_list).apply(lambda d: pd.Timestamp(2020, d.month, d.day)).mean()

输出:

Timestamp('2020-05-12 08:00:00')

从那里,您可以根据需要创建格式化的日期时间对象。