
本文旨在提供一个使用Python计算办公室工作时长的教程,该教程基于CSV数据,无需依赖Pandas库。通过读取包含员工ID、进出类型和时间戳的数据,计算出每个员工在指定月份(例如二月)的工作时长,并以易于理解的格式输出结果。重点在于数据处理、时间计算和结果呈现,并提供代码示例和注意事项。
本教程将指导您如何使用Python计算办公室工作时长,数据来源于CSV文件,且不依赖Pandas库。我们将读取包含员工ID、进出类型(in 或 out)以及时间戳的数据,并计算出每个员工在指定月份(例如二月)的工作时长。
首先,我们需要一个包含员工进出记录的CSV文件。以下是一个示例数据:
id,type,time 1,out,2023-01-01T08:01:28.000Z 1,in,2023-02-01T08:01:28.000Z 2,in,2023-02-01T09:04:16.000Z 2,out,2023-02-01T12:01:28.000Z 1,out,2023-02-01T13:34:15.000Z
将以上数据保存为data.csv文件。
立即学习“Python免费学习笔记(深入)”;
以下是计算办公室工作时长的Python代码:
import datetime
import csv
date_format = '%Y-%m-%dT%H:%M:%S.%fZ'
total_time = {}
feb = datetime.datetime.strptime('2023-02', '%Y-%m').month
file_path = 'data.csv'
with open(file_path, 'r') as f:
# 创建一个CSV读取器
csv_file = csv.DictReader(f)
list_of_dict = list(csv_file)
for d in list_of_dict:
w_id = d['id']
dt = datetime.datetime.strptime(d['time'], date_format).date()
d_time = datetime.datetime.strptime(d['time'], date_format)
if d_time.month == feb:
if not total_time.get(w_id):
total_time[w_id] = {"date": None,"last_in": None, "last_out": None, "work_hour_s": 0. , 'work_hour_string': '' }
update_time = total_time[w_id]
update_time['date'] = dt
if d['type'] == 'in':
update_time['last_in'] = d_time
if d['type'] == 'out':
update_time['last_out'] = d_time
if update_time['last_out'] and update_time['last_in']:
if update_time['last_out'] > update_time['last_in']:
work_hour_s = update_time['last_out'] - update_time['last_in']
update_time['work_hour_s'] += work_hour_s.seconds
up_time = int(update_time['work_hour_s'])
hours, remainder = divmod(up_time, 3600)
minutes, seconds = divmod(remainder, 60)
formatted_duration = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
update_time['work_hour_string'] = formatted_duration
print(total_time)运行以上代码,将得到如下输出:
{'1': {'date': datetime.date(2023, 2, 1),
'last_in': datetime.datetime(2023, 2, 1, 8, 1, 28),
'last_out': datetime.datetime(2023, 2, 1, 13, 34, 15),
'work_hour_s': 19967.0,
'work_hour_string': '05:32:47'},
'2': {'date': datetime.date(2023, 2, 1),
'last_in': datetime.datetime(2023, 2, 1, 9, 4, 16),
'last_out': datetime.datetime(2023, 2, 1, 12, 1, 28),
'work_hour_s': 10632.0,
'work_hour_string': '02:57:12'}}本文提供了一个使用Python计算办公室工作时长的示例代码,该代码不依赖Pandas库,可以直接应用于CSV数据。在实际应用中,需要根据具体情况进行调整和优化,例如处理缺失数据、清洗错误数据以及处理时区问题。通过本文的学习,您应该能够掌握如何使用Python计算办公室工作时长,并将其应用于实际工作中。
以上就是计算Python中的办公室工作时长的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号