英文:
Create a list or array of date time using pandas
问题
我正在尝试使用pandas
在Python中创建一个日期时间列表。我想要类似这样的结果:
2023-05-10_00:00:00
2023-05-10_01:00:00
2023-05-10_02:00:00
.....
.....
2023-05-10_23:00:00
所以基本上我想要带有1小时间隔的日期时间数据。我尝试了以下代码:
dt = pd.to_datetime('2023-05-10', format='%Y-%m-%d')
print(dt)
这给了我以下结果,但不完全符合我的要求:
2023-05-10 00:00:00
我也考虑过创建一个只包含日期2023-05-10
的列表或数组,以及另一个只包含1小时增量的时间数组,然后用下划线_
将它们粘在一起。我不确定如何在Python中做到这一点。
提前感谢您。
英文:
I am trying to create a list of date time in python using pandas
. I want something like:
2023-05-10_00:00:00
2023-05-10_01:00:00
2023-05-10_02:00:00
.....
.....
2023-05-10_23:00:00
So basically I want data with datetime with 1 hour increment. I tried the following
dt = pd.to_datetime('2023-05-10',format='%Y-%m-%d')
print(dt)
which gives me the following, and it is not exactly what I am looking for
2023-05-10 00:00:00
I was also thinking of creating a list or array with just the date 2023-05-10
and another array with only time with 1-hr increment, and then paste them together with a separator _
. I am not sure how to do this in Python.
Thanks in advance.
答案1
得分: 1
import pandas as pd
df = pd.date_range('2023-05-01', '2023-05-02', freq='H')
DatetimeIndex(['2023-05-01 00:00:00', '2023-05-01 01:00:00',
'2023-05-01 02:00:00', '2023-05-01 03:00:00',
'2023-05-01 04:00:00', '2023-05-01 05:00:00',
'2023-05-01 06:00:00', '2023-05-01 07:00:00',
'2023-05-01 08:00:00', '2023-05-01 09:00:00',
'2023-05-01 10:00:00', '2023-05-01 11:00:00',
'2023-05-01 12:00:00', '2023-05-01 13:00:00',
'2023-05-01 14:00:00', '2023-05-01 15:00:00',
'2023-05-01 16:00:00', '2023-05-01 17:00:00',
'2023-05-01 18:00:00', '2023-05-01 19:00:00',
'2023-05-01 20:00:00', '2023-05-01 21:00:00',
'2023-05-01 22:00:00', '2023-05-01 23:00:00',
'2023-05-02 00:00:00'],
dtype='datetime64[ns]', freq='H')
英文:
import pandas as pd
df = pd.date_range('2023-05-01', '2023-05-02', freq='H')
DatetimeIndex(['2023-05-01 00:00:00', '2023-05-01 01:00:00',
'2023-05-01 02:00:00', '2023-05-01 03:00:00',
'2023-05-01 04:00:00', '2023-05-01 05:00:00',
'2023-05-01 06:00:00', '2023-05-01 07:00:00',
'2023-05-01 08:00:00', '2023-05-01 09:00:00',
'2023-05-01 10:00:00', '2023-05-01 11:00:00',
'2023-05-01 12:00:00', '2023-05-01 13:00:00',
'2023-05-01 14:00:00', '2023-05-01 15:00:00',
'2023-05-01 16:00:00', '2023-05-01 17:00:00',
'2023-05-01 18:00:00', '2023-05-01 19:00:00',
'2023-05-01 20:00:00', '2023-05-01 21:00:00',
'2023-05-01 22:00:00', '2023-05-01 23:00:00',
'2023-05-02 00:00:00'],
dtype='datetime64[ns]', freq='H')
答案2
得分: 1
我生成了3个示例数据:
pd.date_range('2023-05-10', periods=3, freq='H').strftime('%Y-%m-%d_%H:%M:%S')
输出:
Index(['2023-05-10_00:00:00', '2023-05-10_01:00:00', '2023-05-10_02:00:00'], dtype='object')
英文:
i make 3 data for example
pd.date_range('2023-05-10', periods=3, freq='H').strftime('%Y-%m-%d_%H:%M:%S')
output:
Index(['2023-05-10_00:00:00', '2023-05-10_01:00:00', '2023-05-10_02:00:00'], dtype='object')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论