我为日期更新编写了代码。 对于原始文件:
12/31/2018 1
12/31/2018 2
12/31/2018 3
12/31/2018 4
12/31/2018 5
12/31/2018 6
12/31/2018 7
12/31/2018 8
12/31/2018 9
12/31/2018 10
12/31/2018 11
12/31/2018 12
12/31/2018 13
12/31/2018 14
12/31/2018 15
12/31/2018 16
12/31/2018 17
12/31/2018 18
12/31/2018 19
12/31/2018 20
12/31/2018 21
12/31/2018 22
12/31/2018 23
12/31/2018 24
12/31/2018 1
12/31/2018 2
12/31/2018 3
12/31/2018 4
12/31/2018 5
12/31/2018 6
12/31/2018 7
第一列是日期,第二列是时间,小时变回1,我想要更新日期。 这是我的代码:
f_r = open("LMP.csv")
f_w = open("LMP_date.csv","w")
f = csv.reader(f_r)
for line in f:
[month,day,year] = line[0].split("/")
if time_ref != 24:
time_ref = int(line[1])
f_w.write(str("%04d%02d%02d" % (int(year),int(month),int(day))) + ',' +line[1]+ ',' +line[2]+ ',' +line[3]+'\n')
else:
time_ref = int(line[1])
day = int(day)+1
leap_year = (int(year)-2000) % 4
if leap_year != 0:
if month in [1,3,5,7,8,10,12]:
if day > 31:
day = 1
month = int(month)+1
if month > 12:
month = 1
year = int(year)+1
if month in [4,6,9,11]:
if day > 30:
day = 1
month = int(month)+1
if month in [2]:
if day > 28:
day = 1
month = int(month)+1
f_w.write("%04d%02d%02d" % (int(year),int(month),int(day)) + ',' +line[1]+ ',' +line[2]+ ',' +line[3]+'\n')
else:
if month in [1,3,5,7,8,10,12]:
if day > 31:
day = 1
month = int(month)+1
if month > 12:
month = 1
year = int(year)+1
if month in [4,6,9,11]:
if day > 30:
day = 1
month = int(month)+1
if month in [2]:
if day > 29:
day = 1
month = int(month)+1
f_w.write("%04d%02d%02d" % (int(year),int(month),int(day)) + ',' +line[1]+ ',' +line[2]+ ',' +line[3]+'\n')
f_r.close()
f_w.close()
但是,我的结果如下所示:
20181231 1
20181231 2
20181231 3
20181231 4
20181231 5
20181231 6
20181231 7
20181231 8
20181231 9
20181231 10
20181231 11
20181231 12
20181231 13
20181231 14
20181231 15
20181231 16
20181231 17
20181231 18
20181231 19
20181231 20
20181231 21
20181231 22
20181231 23
20181231 24
20181232 1
20181231 2
20181231 3
20181231 4
20181231 5
20181231 6
希望有人可以帮助我。我其实想要:
20181231 22
20181231 23
20181231 24
20190101 1
20190101 2
20190101 3
20190101 4
20190101 5
20190101 6
答案 0 :(得分:0)
跟踪每个月的天数等,看起来像是一大堆工作。我建议使用datetime
模块,它将为您处理所有这些细节。
import datetime
#iterate through all days between `start` and `end`
def iter_dates(start, end):
cur_time = start
while cur_time < end:
yield cur_time
cur_time += datetime.timedelta(1)
for date in iter_dates(datetime.datetime(2018, 12, 25), datetime.datetime(2019, 1, 6)):
for i in range(1, 25):
print date.strftime("%Y%m%d"), i
结果:(为简洁起见,部分线被剪掉)
20181225 1
20181225 2
20181225 3
20181225 4
...
20181225 23
20181225 24
20181226 1
20181226 2
...
20181231 23
20181231 24
20190101 1
20190101 2
...
20190105 21
20190105 22
20190105 23
20190105 24