我有两个日期值(可以是任何日期)
start_dt='2019-07-20 00:01'
end_dt='2019-07-24 23:59'
需要生成一个具有以下行的文件
行数=(end_dt-start_dt)是5
start_sequence必须增加50
start_date|end_date|start_sequence
2019-07-20 00:01|2019-07-24 23:59|0
2019-07-20 00:01|2019-07-24 23:59|50
2019-07-20 00:01|2019-07-24 23:59|100
2019-07-20 00:01|2019-07-24 23:59|150
2019-07-20 00:01|2019-07-24 23:59|200
感谢您的帮助,以下是我的Python 2.7的最终工作代码
import csv
from datetime import datetime, timedelta
dt_fmt = "%Y-%m-%d %H:%M"
start_dt = datetime.strptime('2019-07-20 00:01', dt_fmt)
end_dt = datetime.strptime('2019-07-24 23:59', dt_fmt)
num_rows = (end_dt - start_dt)
num_rows += timedelta(hours=1)
with open('out.txt', 'w') as f:
writer = csv.writer(f, delimiter='|')
headers = ['start_date','end_date','start_sequence']
writer.writerow(headers)
for i in range(0, num_rows.days*50, 50):
row = []
row.append(start_dt)
row.append(end_dt)
row.append(i)
writer.writerow(row)
f.close()
答案 0 :(得分:0)
假设您有datetime
个对象并想编写纯文本文件:
from datetime import datetime, timedelta
dt_fmt = "%Y-%m-%d %H:%S"
start_dt = datetime.strptime('2019-07-20 00:01', dt_fmt)
end_dt = datetime.strptime('2019-07-24 23:59', dt_fmt)
num_rows = (end_dt - start_dt)
您的情况下的num_rows.days将为4。如果希望为5,则可能需要根据需要编写舍入算法。这样的事情可能适合您的情况。
num_rows += timedelta(hours=1)
with open('out.txt', 'w') as f:
f.write("start_date|end_date|start_sequence\n")
for i in range(0, num_rows.days*50, 50):
f.write(f"{start_dt}|{end_dt}|{i}\n")
出局:
start_date|end_date|start_sequence
2019-07-20 00:00:01|2019-07-24 23:00:59|0
2019-07-20 00:00:01|2019-07-24 23:00:59|50
2019-07-20 00:00:01|2019-07-24 23:00:59|100
2019-07-20 00:00:01|2019-07-24 23:00:59|150
2019-07-20 00:00:01|2019-07-24 23:00:59|200
答案 1 :(得分:0)
重击:
start_dt='2019-07-20 00:01'
end_dt='2019-07-24 23:59'
start_epoch=`date -d "${start_dt}" +%s`
end_epoch=`date -d "${end_dt}" +%s`
start_sequence=0
for i in `seq 1 $(( (${end_epoch} - ${start_epoch}) / 86400 + 1 ))`
do
echo "${start_dt}|${end_dt}|${start_sequence}"
start_sequence=$(( start_sequence + 50 ))
done