2012-11-23 62 views
1

我的代码是:如何将日期转换为Python中的时间格式?

import datetime 
tomorrow = datetime.date.today() + datetime.timedelta(days=1) 
print "Tomorrow date is" + str(tomorrow) 
tm_stme = datetime.time(0, 0, 0) 
tm_etime = datetime.time(23,59,59) 
tm_stdate = datetime.datetime.combine(tomorrow, tm_stme) 
tm_enddate = datetime.datetime.combine(tomorrow,tm_etime) 

print "tomorrow start date:" + str(tm_stdate) 
print "tomorrow end date:" + str(tm_enddate) 

tm_sdt_convert = time.mktime(time.strptime(tm_stdate, "%Y-%m-%d %H:%M:%S")) 
tm_tdt_convert = time.mktime(time.strptime(tm_enddate, "%Y-%m-%d %H:%M:%S")) 

和错误是:

[email protected]:~/Desktop$ python testing.py 
Tomorrow date is2012-11-24 
tomorrow start date:2012-11-24 00:00:00 
tomorrow end date:2012-11-24 23:59:59 
Traceback (most recent call last): 
    File "testing.py", line 17, in <module> 
    tm_sdt_convert = time.mktime(time.strptime(tm_stdate, "%Y-%m-%d %H:%M:%S")) 
    File "/usr/lib/python2.6/_strptime.py", line 454, in _strptime_time 
    return _strptime(data_string, format)[0] 
    File "/usr/lib/python2.6/_strptime.py", line 322, in _strptime 
    found = format_regex.match(data_string) 
TypeError: expected string or buffer 

我需要tm_sdt_convert变量的值。

回答

4

time.strptime采取一个格式化的字符串,其格式和rerurn包含日期时间信息的元组。 但是,您已经有了一个datetime对象,可以使用方法timetuple直接转换为元组。

所以正确的代码应该是:

>>> tm_sdt_convert = time.mktime(tm_stdate.timetuple()) 
>>> tm_sdt_convert 
1353711600.0 

正确strptime用法:

>>> time.mktime(time.strptime(str(tm_stdate), "%Y-%m-%d %H:%M:%S")) 

有用当你只有一个包含字符串日期时间。

相关问题