gpt4 book ai didi

python - 将范围时间数据转换为 pandas to_datetime 中的日期时间

转载 作者:行者123 更新时间:2023-12-01 03:36:40 24 4
gpt4 key购买 nike

我有一个包含日期和时间数据的数据框“DTime”列:

    01JAN2004 00:00-01:00
01JAN2004 01:00-02:00

我尝试使用以下方法进行解析:

pd.to_datetime(df['DTime'], format='%d%b%Y %H:%M-%H:%M')

但这给出了:

error: redefinition of group name 'H' as group 6; was group 4

我尝试删除“-H:M”,但这会出现“未转换的数据错误”。

有没有办法做到这一点并将时基设置为第一个给定小时?

最佳答案

df = pd.DataFrame([
'01JAN2004 00:00-01:00',
'01JAN2004 01:00-02:00'
], columns=['dstr'])

date_regex = '(?P<date>\d\d\w{3}\d{4})'
beg_regex = '(?P<beg_hour>\d\d):(?P<beg_min>\d\d)'
end_regex = '(?P<end_hour>\d\d):(?P<end_min>\d\d)'
regex = '{} {}-{}'.format(date_regex, beg_regex, end_regex)
d1 = df.dstr.str.extract(regex, expand=True)
for c in ['beg_hour', 'beg_min', 'end_hour', 'end_min']:
d1[c] = d1[c].astype(int)

pd.concat([
pd.to_datetime(d1.date, format='%d%b%Y') + \
pd.to_timedelta(d1.beg_hour, unit='H'),
pd.to_datetime(d1.date, format='%d%b%Y') + \
pd.to_timedelta(d1.beg_hour, unit='H')
], axis=1, keys=['Beg', 'End'])

enter image description here

关于python - 将范围时间数据转换为 pandas to_datetime 中的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266154/

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