Skip to main content
 首页 » 编程设计

python之将 DateTime 转换为一年中的连续日期

2024年10月17日7lvdongjie

我有一个包含一系列日期的数据框,例如:

0    2014-06-17 
1    2014-05-05 
2    2014-01-07 
3    2014-06-29 
4    2014-03-15 
5    2014-06-06 
7    2014-01-29 

现在,我需要一种方法将这些日期转换为一年中的连续日期,例如

0    168 
1    125 
2    7 
3    180 
4    74 
5    157 
7    29 

所有值都在同一年内。 相反的问题已被多次询问 - 将一年中的连续日期转换为日期,但我需要做相反的事情。有没有一种简单的方法可以用 Pandas 做到这一点?谢谢!

编辑:由 piRSquared 回答。谢谢!

请您参考如下方法:

选项 1
time-date-components
链接来自@root
使用 dt.dayofyear

df.iloc[:, 0].dt.dayofyear 
 
0    168 
1    125 
2      7 
3    180 
4     74 
5    157 
7     29 
Name: 1, dtype: int64 

选项 2
strftime.org
使用 dt.strftime('%-j')

df.iloc[:, 0].dt.strftime('%-j') 
 
 
0    168 
1    125 
2      7 
3    180 
4     74 
5    157 
7     29 
Name: 1, dtype: object