输入import 这里用datetime和random
import csv
import datetime
import random
设置随机时间的范围
start_year = 2004
end_year = 2023
start_month = 1
end_month = 12
start_day = 1
end_day = 27
start_hour = 0
end_hour = 23
start_minute = 0
end_minute = 59
start_second = 0
end_second = 59
读取CSV文件
with open(r’C:\Users\ASUS\favorite_song_list.csv’, ‘r’, encoding=‘utf-8’) as file:
reader = csv.reader(file)
rows = list(reader)
生成随机时间列表
random_times = []
for _ in rows:
# 生成随机的年、月、日、时、分、秒
year = random.randint(start_year, end_year)
month = random.randint(start_month, end_month)
day = random.randint(start_day, end_day)
hour = random.randint(start_hour, end_hour)
minute = random.randint(start_minute, end_minute)
second = random.randint(start_second, end_second)
# 创建随机时间对象
random_time = datetime.datetime(year, month, day, hour, minute, second)
# 将随机时间转换为字符串格式
random_time_str = random_time.strftime('%Y-%m-%d %H:%M:%S')
random_times.append(random_time_str)
将随机时间列添加到数据的最后一列
for row in rows:
row.append(random_times.pop(0))
将更新后的数据写回CSV文件
with open(r’C:\Users\ASUS\favorite_song_list.csv’, ‘w’, encoding=‘utf-8’) as file:
writer = csv.writer(file)
writer.writerows(rows)
print(‘CSV文件已更新,最后一列已添加随机日期时间。’)