比较Python中的datetime.time和pd.TimeStamp

2024-05-23 20:14:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,其中pd.TimeStamp数据包含在CRASH TIME列中,例如Timestamp('2017-06-26 22:00:00')。我创建了一个名为SUNRISE的新列,其中包含datetime数据,例如datetime.time(5, 26, 50, 135154)

我想比较一下CRASH TIMESUNRISE的时间,以确定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.TimeStampdatetime.time?我知道我可以用here找到的技术执行apply(),但我觉得有一种更面向熊猫的方法


Tags: 数据dfdatetimetime方式时间crashtimestamp
1条回答
网友
1楼 · 发布于 2024-05-23 20:14:38

您可以使用Series.dt.time方法将pandasTimeStamps转换为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, 26, 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]))

产出->

           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'>

enter image description here

相关问题 更多 >