我有一个包含日期和时间数据的数据框“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'])
关于python - 将范围时间数据转换为 pandas to_datetime 中的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266154/