我是Python新手,很难将经过的时间累积到一个变量中。数据来自时间和出勤计划。我所要寻找的是在给定的时间段内工作的总时间,给定每个记录中的开始日期/时间和结束日期/时间。我的代码如下:
import pyodbc
import datetime
import time
fname = "\\frontofficezdata.mdb"
sname = "\\frontofficezsecured.mdw"
connect_string = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + fname +";UID=me;PWD=password;systemDB=" + sname + ";"
cnxn = pyodbc.connect(connect_string)
cursor = cnxn.cursor()
SQL = "SELECT EmpID, Weekending, Department, PayType, StartTime, EndTime FROM EmpHours WHERE EmpID=" + str(1) + " AND Weekending = #28/03/2015#;"
ttime = 0.0
for timerec in cursor.execute(SQL):
print timerec.Department, timerec.PayType,
if timerec.StartTime is not None:
print timerec.StartTime,
else:
print "",
if timerec.EndTime is not None:
print timerec.EndTime,
else:
print "",
if timerec.StartTime is not None and timerec.EndTime is not None:
print timerec.EndTime - timerec.StartTime
#ttime = ttime + timerec.EndTime - timerec.StartTime
print ttime
else:
print "n/a"
我的输出是:
Admin Regular 2015-03-23 17:04:33 2015-03-23 17:04:41 0:00:08
0.0
Admin Regular 2015-03-23 17:04:51 2015-03-23 17:04:57 0:00:06
0.0
Admin Regular 2015-03-23 17:05:04 n/a
Admin Regular 2015-03-23 17:05:13 2015-03-23 17:05:20 0:00:07
0.0
Admin Regular 2015-03-23 17:05:26 2015-03-23 17:05:33 0:00:07
0.0
Admin Regular 2015-03-23 17:06:09 2015-03-23 17:06:15 0:00:06
0.0
Admin Regular 2015-03-23 17:06:22 2015-03-23 17:06:28 0:00:06
0.0
Admin Regular 2015-03-23 17:06:35 2015-03-23 17:06:42 0:00:07
0.0
Admin Regular 2015-03-23 17:07:17 2015-03-23 17:07:23 0:00:06
0.0
Admin Regular 2015-03-23 17:07:29 2015-03-23 17:07:35 0:00:06
0.0
Admin Regular 2015-03-23 17:07:42 2015-03-23 17:07:48 0:00:06
0.0
Admin Regular 2015-03-23 17:08:45 2015-03-23 17:08:52 0:00:07
0.0
Admin Regular 2015-03-23 17:08:59 2015-03-23 17:09:05 0:00:06
0.0
我似乎无法更改时间记录。StartTime/EndTime为自epoch以来的秒,也不能将时间初始化为空的datetime.datetime变量。有什么想法吗?
您已经有了datetime.datetime()
对象,减去它们就得到了datetime.timedelta()
。对这些对象求和:
ttime = datetime.timedelta()
for timerec in cursor.execute(SQL):
if timerec.StartTime and timerec.EndTime:
ttime += timerec.EndTime - timerec.StartTime
在for
循环结束时,ttime
是代表总工作时间的timedelta()
对象。您可以用将其表示为秒数
ttime_seconds = ttime.total_seconds()
您也可以在SQL级别执行此操作,这可能更容易:
SQL = "SELECT EmpID, Weekending, Department, PayType, StartTime, EndTime, DATEDIFF(SECOND, StartTime, EndTime) AS SecondDiff FROM EmpHours WHERE EmpID=" + str(1) + " AND Weekending = #28/03/2015#;"
将SECOND替换为MINUTE、WEEK、YEAR或您需要的任何内容。祝你好运