gpt4 book ai didi

Pandas : How to get timestamp. 天和 timestamp.month 填充零

转载 作者:行者123 更新时间:2023-12-02 17:28:45 28 4
gpt4 key购买 nike

rng = pd.date_range('2016-02-07', periods=7, freq='D')
print(rng[0].day)
print(rng[0].month)

7
2

我想要用零填充的输出。即:

07
02

a)有没有现成的函数可以改变.day和.month的格式?

b)有没有其他方法可以用补零来获取日期和月份?

我已经尝试过以下方法:

rng = pd.date_range('2016-02-07', periods=7, freq='D')
r=str(rng[0])

d = datetime.strptime(r[:10], '%Y-%m-%d') #[:10] this removes time from date
z= (date.strftime(d, "%d"))
print(z)

输出:

07

谢谢。

最佳答案

您可以使用 IIUC strftime :

In [8]:
rng = pd.date_range('2016-02-07', periods=7, freq='D')
days = rng.strftime('%d')
months = rng.strftime('%m')
print(days)
print(months)

['07' '08' '09' '10' '11' '12' '13']
['02' '02' '02' '02' '02' '02' '02']

关于Pandas : How to get timestamp. 天和 timestamp.month 填充零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36383026/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com