[英]How do you convert a Time Range (19:00-20:00) to a TimeStamp/Date Time object?
My DF has a Column Time with a range of 1 hour.我的 DF 有一个范围为 1 小时的列时间。 19:00-20:00, 20:00-21:00, 21:00-22:00 and so on.
19:00-20:00、20:00-21:00、21:00-22:00等。 I have another Column with a recorded Value in these Times, like 50 , 40, 10.
我有另一个列在这些时间中记录了值,例如 50 、 40 、 10 。
I want to know at what Hour of the Day is the Value the highest etc.. Is there a way I can convert the time from range to just single value like 19:00 and then extract the hour?我想知道一天中哪个小时的值最高等等。有没有办法可以将时间从范围转换为单个值,例如 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
First use Series.str.split
and then convert values to timedeltas by to_timedelta
:首先使用
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
Or to datetimes by to_datetime
:或者通过
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
Here is possible easy way extract parts of datetimes, eg hours, times...:这是提取日期时间部分的可能简单方法,例如小时,时间......:
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.