0

我想用日期归档我的文件,但我有 02 个问题:

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta


fo = open("dattes.txt","wb")
for result in perdelta(date(2011, 10, 10), date(2011, 12, 12), timedelta(days=4)):
    fo.write(result)


fo.close()

1-我收到此错误:

Traceback(最近一次调用最后一次):文件“C:\test\date.txt”,第 12 行,在 fo.write(result) 类型错误:必须是字符串或缓冲区,而不是 datetime.date

2-我希望输出日期是连续的(在日、月和年之间没有“-”)

4

2 回答 2

2

一项更改将解决这两个问题:

fo.write(result.strftime('%Y%m%d\n'))
于 2013-08-10T14:15:39.673 回答
2

使用datetime.date.strftime格式化日期。

如果你不想,你可能想在中间写 newline( '\n') 201110102011101420111018....

所以,

...
for result in perdelta(date(2011, 10, 10), date(2011, 12, 12), timedelta(days=4)):
    fo.write(result.strftime('%Y%m%d\n'))
....

选择

...
for result in perdelta(date(2011, 10, 10), date(2011, 12, 12), timedelta(days=4)):
    fo.write('{0:%Y%m%d}\n', result)
...
于 2013-08-10T14:15:50.873 回答