2013-03-21 35 views
0

在尝试运行这段代码我得到Debian的一个错误,但它适用于Windows。日期时间工作在Windows,但不是Debian的

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 

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

+4

你为什么将今天的日期为一个字符串,然后再次将其转换为datetime,然后将其再次转换为字符串再次,只有将其转换为datetime对象? – 2013-03-21 10:07:55

+0

科学!或者更现实的解释是,我倾向于使事情复杂化。 – Leinad177 2013-03-21 12:40:13

回答

2

你的日期处理方式是过于复杂。

这应该在任何平台上做精:

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

.strip()调用中删除任何多余的空格(从Windows格式\r\n CRNL组合如\r线)。

我不确定为什么你要经过这么长的时间才能将今天的日期转换为字符串,并将其解析为一个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) 

通过在datetime.datetime实例调用.date()可以再次得到一个datetime.date对象:

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

谢谢。这解释得很好。 – Leinad177 2013-03-21 12:40:33

1

这可能是因为 'date.txt' 包含Windows风格的行结束符( '\ r \ n'),而UNIX(Debian的)仅处理 '\ n'。

尝试使用通用线路打开你的文件结尾:

open('date.txt','U') 
相关问题