繁体   English   中英

如何将时间范围 (19:00-20:00) 转换为时间戳/日期时间对象?

[英]How do you convert a Time Range (19:00-20:00) to a TimeStamp/Date Time object?

我的 DF 有一个范围为 1 小时的列时间。 19:00-20:00、20:00-21:00、21:00-22:00等。 我有另一个列在这些时间中记录了值,例如 50 、 40 、 10 。

我想知道一天中哪个小时的值最高等等。有没有办法可以将时间从范围转换为单个值,例如 19:00,然后提取小时?

Df['Time'] = pd.to_datetime(Df['Time']) I tried this but got error 

Out of bounds nanosecond timestamp: 1-01-01 19:00:00

首先使用Series.str.split ,然后通过to_timedelta将值转换为to_timedelta

df = pd.DataFrame({'Time':['19:00-20:00', '20:00-21:00', '21:00-22:00']})

df[['first', 'second']] = (df['Time'].str.split('-', expand=True)
                                     .add(':00')
                                     .apply(pd.to_timedelta))
print (df)
          Time    first   second
0  19:00-20:00 19:00:00 20:00:00
1  20:00-21:00 20:00:00 21:00:00
2  21:00-22:00 21:00:00 22:00:00

print (df.dtypes)
Time               object
first     timedelta64[ns]
second    timedelta64[ns]
dtype: object

或者通过to_datetime到日期to_datetime

df[['first', 'second']] = df['Time'].str.split('-', expand=True).apply(pd.to_datetime)
print (df)
          Time               first              second
0  19:00-20:00 2019-08-04 19:00:00 2019-08-04 20:00:00
1  20:00-21:00 2019-08-04 20:00:00 2019-08-04 21:00:00
2  21:00-22:00 2019-08-04 21:00:00 2019-08-04 22:00:00

print (df.dtypes)
Time              object
first     datetime64[ns]
second    datetime64[ns]
dtype: object

这是提取日期时间部分的可能简单方法,例如小时,时间......:

df['hour1'] = df['first'].dt.hour
df['time1'] = df['first'].dt.time
print (df)
          Time               first              second  hour1     time1
0  19:00-20:00 2019-08-04 19:00:00 2019-08-04 20:00:00     19  19:00:00
1  20:00-21:00 2019-08-04 20:00:00 2019-08-04 21:00:00     20  20:00:00
2  21:00-22:00 2019-08-04 21:00:00 2019-08-04 22:00:00     21  21:00:00

print (df.dtypes)
Time              object
first     datetime64[ns]
second    datetime64[ns]
hour1              int64
time1             object
dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM