读取图书信息和读者信息,批量生成图书借阅记录并导随机时间借阅记录代码
时间: 2023-12-12 08:04:16 浏览: 79
要生成随机时间的图书借阅记录,可以使用`random`模块来生成随机日期和时间。以下是一个示例代码:
```python
import csv
from datetime import datetime, timedelta
import random
def generate_random_datetime(start_date, end_date):
# 生成指定范围内的随机日期和时间
start_timestamp = start_date.timestamp()
end_timestamp = end_date.timestamp()
random_timestamp = random.uniform(start_timestamp, end_timestamp)
random_datetime = datetime.fromtimestamp(random_timestamp)
return random_datetime
def generate_borrow_records(books_file, readers_file, borrow_records_file, start_date, end_date):
# 读取图书信息
books = []
with open(books_file, 'r') as file:
reader = csv.DictReader(file)
books = list(reader)
# 读取读者信息
readers = []
with open(readers_file, 'r') as file:
reader = csv.DictReader(file)
readers = list(reader)
# 生成借阅记录
borrow_records = []
for book in books:
for reader in readers:
borrow_date = generate_random_datetime(start_date, end_date)
return_date = borrow_date + timedelta(days=random.randint(7, 30))
borrow_record = {
'Book ID': book['ID'],
'Book Name': book['Name'],
'Reader ID': reader['ID'],
'Reader Name': reader['Name'],
'Borrow Date': borrow_date.strftime('%Y-%m-%d %H:%M:%S'),
'Return Date': return_date.strftime('%Y-%m-%d %H:%M:%S')
}
borrow_records.append(borrow_record)
# 导出借阅记录
fieldnames = ['Book ID', 'Book Name', 'Reader ID', 'Reader Name', 'Borrow Date', 'Return Date']
with open(borrow_records_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(borrow_records)
# 示例用法
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 12, 31)
generate_borrow_records('books.csv', 'readers.csv', 'borrow_records.csv', start_date, end_date)
```
上述代码中,`generate_random_datetime`函数用于生成指定范围内的随机日期和时间。在`generate_borrow_records`函数中,我们使用该函数来生成随机的借阅日期和还书日期。借阅日期随机生成,还书日期在借阅日期基础上随机增加7到30天。最后,将借阅记录导出到CSV文件中。
请注意,上述代码中的日期范围和文件路径需要根据实际情况进行调整。另外,如果需要更复杂的日期和时间生成,您可能需要使用更高级的日期和时间库,如`arrow`或`dateutil`。
阅读全文