Datetime适用于Windows,但不适用于Debian

时间:2013-03-21 10:05:46

标签: python datetime debian

尝试运行此代码时,我在Debian上收到错误,但它适用于Windows。

def checkTime():
    while True:
        with open('date.txt') as tar:
            target = tar.read()
            current = str(datetime.strptime(str(date.today()),'%Y-%m-%d'))[:-9]
            if datetime.strptime(current, '%Y-%m-%d') >= datetime.strptime(target, '%Y-%m-%d'):
                doSomething()
        sleep(10)

它给了我这个错误:

File "/usr/lib/python2.6/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

date.txt包含:

2013-03-21

两个系统都具有完全相同的日期和时间设置。

2 个答案:

答案 0 :(得分:2)

您的日期处理过于复杂。

这应该可以在任何平台上运行:

with open('date.txt') as tar:
    target = tar.read().strip()
    if date.today() >= datetime.strptime(target, '%Y-%m-%d').date():

.strip()调用删除任何无关的空格(例如来自Windows格式\r CRNL组合的\r\n行。)

我不确定你为什么要花这么多时间将今天的日期转换为字符串,将其解析为datetime对象,然后再将其转换为字符串。在任何情况下,datetime.date对象的默认字符串格式都遵循ISO8601,与%Y-%m-%d格式匹配:

>>> import datetime
>>> str(datetime.date.today())
'2013-03-21'

要将datetime.date对象转换为datetime.datetime对象,请使用.combine()方法并在混合中添加datetime.time对象:

>>> datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime(2013, 3, 21, 0, 0)

通过在.date()个实例上调用datetime.datetime,您可以再次获得datetime.date个对象:

>>> datetime.datetime.now().date()
datetime.date(2013, 3, 21)

答案 1 :(得分:1)

这可能是因为'date.txt'包含Windows样式的行结尾('\ r \ n'),但Unix(Debian)只处理'\ n'。

尝试使用通用线路端打开文件:

open('date.txt','U')