我的df看起来像这样:
Time_Start CODE time
0 2018-01-31 16:45:04.263 B76 2018-01-31 16:48:06
1 2018-01-31 16:10:26.000 974 2018-01-31 16:50:06
我从time
中减去Time_Start
。对于第二个,我得到39:49这是预期的输出但是对于第一个我得到的数字像2.737000(不是我想要的)。
Time_Start
为datetime64[ns]
,time
为object
。这就是我进行转换和减法的方式:
waiting['time'] = pd.to_datetime(waiting['time'])
waiting['Duration'] = waiting['time'] - waiting['Time_Start']
waiting['Duration'] = waiting['Duration'].apply(lambda x: str(x)[-8:])
我对python很新,所以有人能告诉我我做错了什么以及为什么我得到了2个不同的输出? 我正在使用python 2.x。
完整代码:
query that returns the dataframe
.......
end_time = np_server_date.ix[0]['data'] """current time"""
end_time = end_time.strftime('%Y-%m-%d %H:%M:%S')
waiting['time'] = end_time """it's now the current time"""
waiting['time'] = pd.to_datetime(waiting['time'])
waiting['Duration'] = waiting['time'] - waiting['Time_Start']
waiting['Duration'] = waiting['Duration'].apply(lambda x: str(x)[-8:])
答案 0 :(得分:0)
好的,所以我觉得我现在有足够的信息来回答你的问题。
蝙蝠的权利,你需要create a connection with pyodbc。
然后,您希望循环遍历结果集,然后通过构造函数或使用两次strptime()创建datetime对象。
然后,您将减去日期时间对象以获得作为timedelta对象的时间之间的差异。
然后,根据您需要对该信息执行的操作,您可以通过数学运算将其转换为您的格式。
import datetime
import pyodbc
#create connection
with pyodbc.connect(db, password) as cnxn:
#create cursor
cursor = cnxn.cursor()
cursor.execute('YOUR QUERY')
#loop through results
while true:
#use fetchone generator to optimize memory usage
row = cursor.fetchone()
#create datetime objects
start_time = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S.%f')
end_time = datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S')
#the following creates a timedelta object
time_diff = end_time - start_time
#a couple ways to deal with the result
#printing time_diff yields Days:Seconds:Microseconds
#the following yields the difference in seconds
#difference = time_diff.totalseconds()
#alternatively, you can get days, seconds, microseconds.
#either way you have to do some math to convert to hours and
#minutes if desired
#difference = time_diff.days + ":" + time_diff.seconds + ":"
# + time_diff.microseconds
#TODO your division to format the seconds how you'd like
#using divmod, you can get hours, min, second
m, s = divmod(time_diff.seconds, 60)
h, m = divmod(m, 60)
print "%d:%d:%02d:%02d" % (time_diff.days, h, m, s)
#TODO whatever you need to do with this information
if not row:
break