如何解决在Python中比较datetime.time和pd.TimeStamp
我有一个pd.TimeStamp
列中包含CRASH TIME
数据的数据集,例如Timestamp('2017-06-26 22:00:00')
。我创建了一个名为SUNRISE
的新列,其中包含datetime
数据,例如datetime.time(5,26,50,135154)
。
我想比较CRASH TIME
和SUNRISE
的时间,以确定CRASH TIME
中的时间是日出之前还是之后。当我尝试通过以下方式进行操作时:
df['DAYTIME'] = 0
after_sunrise = df['CRASH TIME'] > df['SUNRISE']
df.loc[after_sunrise == True,'DAYTIME'] = 1
我收到一个错误:TypeError: '>' not supported between instances of 'Timestamp' and 'datetime.time'
。如何比较pd.TimeStamp
和datetime.time
?我知道我可以使用here的技术执行apply()
,但是我觉得还有一种面向熊猫的方法。
解决方法
您可以使用Series.dt.time
方法将熊猫TimeStamps
转换为datetime.time
对象,然后其他事情很简单:
import pandas as pd
import numpy as np
from datetime import time
#Create fake dataset
df = pd.DataFrame()
df["CRASH TIME"] = pd.to_datetime(['2017-06-26 22:00:00','2017-06-27 21:50:00'])
df["SUNRISE"] = [time(22,26,50,135154),time(21,49,135154)]
print(df.head())
print("CRASH TIME element type:",type(df["CRASH TIME"][0]))
print("SUNRISE element type:",type(df["SUNRISE"][0]))
df["CRASH TIME"] = df["CRASH TIME"].dt.time
print("CRASH TIME element type:",type(df["CRASH TIME"][0]))
Output->
CRASH TIME SUNRISE
0 2017-06-26 22:00:00 22:26:50.135154
1 2017-06-27 21:50:00 21:26:49.135154
CRASH TIME element type: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
SUNRISE element type: <class 'datetime.time'>
CRASH TIME element type: <class 'datetime.time'>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。