我有以下日期清单:
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”。
发布于 2022-01-26 00:36:38
你得到这个平均数是因为考虑到了这一年。为了得到想要的结果,您需要用相同的年份构造新的时间戳。
也许有一个更优雅的解决方案,但这里有一个应该工作得很好的解决方案:
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')在那里,您可以创建格式化为任何格式的datetime对象。
https://stackoverflow.com/questions/70857235
复制相似问题