gpt4 book ai didi

Python datetime 到日期和时间

转载 作者:行者123 更新时间:2023-12-04 15:16:29 25 4
gpt4 key购买 nike

我想从数据框的日期时间索引中提取日期和时间。

我的代码:

df.index = DatetimeIndex(['2020-07-07 19:03:38', '2020-07-08 18:50:40',
'2020-07-24 4:20:13', '2020-07-25 4:20:13'],
dtype='datetime64[ns]', name='datetime', freq=None)

print(df.index.strftime('%d %h:%m')

是否有默认的方法来获取类似 .date 的方法?

最佳答案

只需使用 pd.to_datetime 而不是 DatetimeIndex。正如 Trenton McKinney 在评论中指出的那样,它应该是 strftime 中的 HM:

import pandas as pd
from datetime import datetime

data = {'stuff': [0,1,2,3]}
df = pd.DataFrame(data)

df.index = pd.to_datetime(['2020-07-07 19:03:38', '2020-07-08 18:50:40',
'2020-07-24 4:20:13', '2020-07-25 4:20:13']).strftime('%d %H:%M')

print(df)

stuff
07 19:03 0
08 18:50 1
24 04:20 2
25 04:20 3

关于Python datetime 到日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64248208/

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