python - 如何在Python中将时间差累积到变量中

标签 python pyodbc python-datetime

我是一个Python新手,我真的很难将一些耗时累积到一个变量中。该数据来自考勤程序。我所寻找的是每条记录中给定开始日期/时间和结束日期/时间的给定期间内的总工作时间。我的代码如下:

import pyodbc
import datetime 
import time

fname = "\\\\frontoffice\z\data.mdb"
sname = "\\\\frontoffice\z\secured.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

我似乎无法将timerec.StartTime/EndTime更改为自纪元以来的秒数,也无法将ttime初始化为空的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()

关于python - 如何在Python中将时间差累积到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29261991/

相关文章:

python - 日期时间 : ValueError: day is out of range for month

python - Tic-Tac-Toe 游戏 Python 的 for 循环中的迭代是如何工作的?

python - Linux Python Azure Function APP - 尽管在 requirements.txt 和其他模块中工作正常,但找不到 pyodbc 模块

python - 我怎么能只比较 dd/mm 和 dd/mm/yyyy 在 Google 表格中?

python - pyodbc 中的清理查询仅返回字段名称

Python访问具有动态获取的列名的单元格

python - 我怎样才能得到 Python 的前一周?

python - 将 DataFrame 列类型从字符串转换为日期时间

python - Windows 上的 Pocketsphinx-python 安装错误

python - 从字典 python 中删除 'Counter'